WPF-控件属性相对路径绑定

在WPF中,我们想要绑定数据可以象这样直接绑定

Text="{Binding Path=Name}"

 

但是如果在ListBox的DataTemplate中我们想要绑定ListBoxItem的一个属性,需要使用RelativeSource来寻找我们要找的元素。如下。

Foreground="{Binding Path=(ListBoxItem.Foreground), RelativeSource={RelativeSource Mode=FindAncestor, AncestorLevel=1, AncestorType={x:Type ListBoxItem}}}"

 

想要一个TextBlock的Foreground和ListBoxItem的Foreground相同。

使用Path指定ListBoxItem.Foreground,表明想要绑定的属性。

使用RelativeSource来寻找指定的ListBoxItem,Mode为FindAncestor(寻找祖先),表明查找的是父级元素,AncestorType为设置ListBoxItem的类型,表明我们要查找的父级元素的类型。AncestorLevel为1,表明要找的是第几个类型为ListBoxItem的父级元素,按照查找的方向。

 

posted @ 2021-03-14 00:01  Watt不想上班  阅读(469)  评论(0编辑  收藏  举报