绑定中的 WPF FindAncestor
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16278284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF FindAncestor in binding
提问by dbostream
One particular thing about FindAncestor confuses me, have a look at the example below:
FindAncestor 的一个特别之处让我感到困惑,请看下面的示例:
<Expander.HeaderTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Label Name="headerLabel" Content="Show Contents" Padding="0" VerticalAlignment="Center" />
<Button Name="headerButton" Margin="6,0,0,0" Content="Button" Padding="6,1" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=IsExpanded}" Value="True">
<Setter TargetName="headerLabel" Property="Content" Value="Hide Contents" />
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</Expander.HeaderTemplate>
I use the xaml above to change the text of my custom expander header. My question is, when do I actually need to explicitly use FindAncestor when I want to use a property of an ancestor in my binding? Because the following three bindings appear to yield the same result in my scenario at least:
我使用上面的 xaml 来更改我的自定义扩展器标题的文本。我的问题是,当我想在绑定中使用祖先的属性时,我什么时候真正需要显式使用 FindAncestor?因为至少在我的场景中,以下三个绑定似乎会产生相同的结果:
Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=IsExpanded}"
Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Expander}}, Path=IsExpanded}"
Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type Expander}}, Path=IsExpanded}"
I have seen lots of examples of all three, is it just a matter of personal taste?
我看过很多这三个的例子,这只是个人品味的问题吗?
回答by GazTheDestroyer
From the MSDN page about the RelativeSource.Mode
property:
从关于该RelativeSource.Mode
属性的 MSDN 页面:
If this property is not set explicitly, setting the AncestorType or the AncestorType and the AncestorLevel properties will implicitly lock this property value to FindAncestor.
如果未显式设置此属性,则设置 AncestorType 或 AncestorType 和 AncestorLevel 属性将隐式锁定此属性值到 FindAncestor。