我如何使用WPF绑定的RelativeSource,有哪些不同的用例?


当前回答

值得注意的是,对于那些无意中发现Silverlight的想法的人:

Silverlight只提供了这些命令的一个简化子集

其他回答

我没有阅读每个答案,但我只是想添加这个信息,以防按钮的相对源命令绑定。

当你使用Mode= find祖宗的相对源时,绑定必须像这样:

Command="{Binding Path=DataContext.CommandProperty, RelativeSource={...}}"

如果你没有在你的路径中添加DataContext,在执行时它不能检索属性。

不要忘记TemplatedParent:

<Binding RelativeSource="{RelativeSource TemplatedParent}"/>

or

{Binding RelativeSource={RelativeSource TemplatedParent}}

值得注意的是,对于那些无意中发现Silverlight的想法的人:

Silverlight只提供了这些命令的一个简化子集

如果你想绑定到对象上的另一个属性:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

如果你想获取一个祖先的属性:

{Binding Path=PathToProperty,
    RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

如果你想在父模板上获得一个属性(所以你可以在一个ControlTemplate中做2种方式绑定)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

或者更短(这只适用于OneWay绑定):

{TemplateBinding Path=PathToProperty}

这是我在空数据网格上使用该模式的一个示例。

<Style.Triggers>
    <DataTrigger Binding="{Binding Items.Count, RelativeSource={RelativeSource Self}}" Value="0">
        <Setter Property="Background">
            <Setter.Value>
                <VisualBrush Stretch="None">
                    <VisualBrush.Visual>
                        <TextBlock Text="We did't find any matching records for your search..." FontSize="16" FontWeight="SemiBold" Foreground="LightCoral"/>
                    </VisualBrush.Visual>
                </VisualBrush>
            </Setter.Value>
        </Setter>
    </DataTrigger>
</Style.Triggers>