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


当前回答

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

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

其他回答

我创建了一个库来简化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的例子会更长。

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

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

不要忘记TemplatedParent:

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

or

{Binding RelativeSource={RelativeSource TemplatedParent}}

一些有用的小片段:

以下是如何主要在代码中做到这一点:

Binding b = new Binding();
b.RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, this.GetType(), 1);
b.Path = new PropertyPath("MyElementThatNeedsBinding");
MyLabel.SetBinding(ContentProperty, b);

我很大程度上复制了这从绑定相对源在代码后面。

同样,就示例而言,MSDN页面也很不错:RelativeSource Class

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

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