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


当前回答

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

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

其他回答

我创建了一个库来简化WPF的绑定语法,包括让它更容易使用RelativeSource。这里有一些例子。之前:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}
{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}
{Binding Path=Text, ElementName=MyTextBox}

后:

{BindTo PathToProperty}
{BindTo Ancestor.typeOfAncestor.PathToProperty}
{BindTo Template.PathToProperty}
{BindTo #MyTextBox.Text}

下面是一个如何简化方法绑定的示例。之前:

// C# code
private ICommand _saveCommand;
public ICommand SaveCommand {
 get {
  if (_saveCommand == null) {
   _saveCommand = new RelayCommand(x => this.SaveObject());
  }
  return _saveCommand;
 }
}

private void SaveObject() {
 // do something
}

// XAML
{Binding Path=SaveCommand}

后:

// C# code
private void SaveObject() {
 // do something
}

// XAML
{BindTo SaveObject()}

你可以在这里找到图书馆:http://www.simplygoodcode.com/2012/08/simpler-wpf-binding.html

请注意,在我用于方法绑定的“BEFORE”示例中,代码已经通过使用RelayCommand进行了优化,我最后检查它不是WPF的本机部分。没有这个BEFORE的例子会更长。

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

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

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

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

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

在WPF中,RelativeSource绑定公开了三个属性来设置:

1. Mode:这是一个枚举,可以有四个值:

a. PreviousData(value=0):它将属性的上一个值赋给 约束函数 b. TemplatedParent(value=1):在定义的模板时使用 任何控件,并希望绑定到控件的值/属性。 例如,定义ControlTemplate:

  <ControlTemplate>
        <CheckBox IsChecked="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Value, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
 </ControlTemplate>

c. Self(value=2):当我们想从一个Self或Self的属性绑定时。 例如:在设置复选框上的命令时,将复选框的选中状态发送为CommandParameter

<CheckBox ...... CommandParameter="{Binding RelativeSource={RelativeSource Self},Path=IsChecked}" />

d. FindAncestor(value=3):当想从父控件绑定时 在可视化树中。 例如:在记录中绑定一个复选框,如果选中了网格,如果选中了标题复选框

<CheckBox IsChecked="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}, Path=DataContext.IsHeaderChecked, Mode=TwoWay}" />

2. 祖宗类型:当模式是find祖宗,然后定义什么类型的祖先

RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid}}

3.祖宗级别:当模式是FindAncestor时,那么祖先的级别是什么(如果在可视树中有两个相同类型的父)

RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type iDP:XamDataGrid, AncestorLevel=1}}

以上是RelativeSource绑定的所有用例。

这里有一个参考链接。