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


当前回答

我刚刚发布了另一个在Silverlight中访问父元素的DataContext的解决方案。它使用Binding ElementName。

其他回答

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

<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>

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

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

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

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

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

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

Binding RelativeSource={
    RelativeSource Mode=FindAncestor, AncestorType={x:Type ItemType}
}
...

RelativeSource的默认属性是Mode属性。这里给出了一组完整的有效值(来自MSDN):

PreviousData Allows you to bind the previous data item (not that control that contains the data item) in the list of data items being displayed. TemplatedParent Refers to the element to which the template (in which the data-bound element exists) is applied. This is similar to setting a TemplateBindingExtension and is only applicable if the Binding is within a template. Self Refers to the element on which you are setting the binding and allows you to bind one property of that element to another property on the same element. FindAncestor Refers to the ancestor in the parent chain of the data-bound element. You can use this to bind to an ancestor of a specific type or its subclasses. This is the mode you use if you want to specify AncestorType and/or AncestorLevel.

下面是MVVM架构的一个更直观的解释: