绑定Setter.Value代码

dev*_*os1 7 c# wpf setter binding code-behind

在XAML中我可以这样写:

<Setter Property="PropertyName" Value="{Binding ...}" />
Run Code Online (Sandbox Code Playgroud)

我将如何在代码中执行此操作?我之前在代码中构造了绑定,但我似乎无法ValuePropertySetter类上找到任何要传递给它的静态对象BindingOperations.SetBinding().

Ray*_*rns 13

在Setter上设置绑定时,根本不需要BindingOperations.你需要做的就是:

var setter = new Setter(TextBlock.TextProperty, new Binding("FirstName"));
Run Code Online (Sandbox Code Playgroud)

或者等价的

var setter = new Setter
{
  Property = TextBlock.TextProperty,
  Value = new Binding("FirstName"),
};
Run Code Online (Sandbox Code Playgroud)

这些中的任何一个都相当于

<Setter Property="TextBlock.Text" Value="{Binding FirstName}" />
Run Code Online (Sandbox Code Playgroud)

这样做的原因是Setter.Value是一个普通的CLR属性,而不是DependencyProperty,因此它不能被绑定.因此,当您在其中存储Binding对象时,XAML或代码中都不存在歧义.

当Setter实际应用于对象时,如果在Setter中找到Binding,则调用BindingOperations.SetBinding的等效项.否则,酒店将直接设置.