WPF - 从代码隐藏/附加行为绑定到显式实现的接口属性

mic*_*eyt 6 c# data-binding wpf xaml

我试图从代码隐藏设置绑定到显式实现的接口属性.代码隐藏绑定的原因是绑定属性的路径只能在运行时确定.

在XAML中,可以这样绑定(在MainWindow.xaml中的示例):

<TextBox Text="{Binding (local:IViewModel.Property)}"/>
Run Code Online (Sandbox Code Playgroud)

事实上,在代码背后的绑定以类似的方式工作(来自MainWindow.xaml.cs):

var binding = new Binding("(local:IViewModel.Property)");
Run Code Online (Sandbox Code Playgroud)

因为WPF能够获取命名空间映射.

我的问题是,当命名空间映射不存在时(例如,在附加行为中),如何形成这样的绑定?

提前谢谢了!

Ken*_*art 9

你会指定一个完整的PropertyPath:

var propertyInfo = typeof(IViewModel).GetProperty("Property");
var propertyPath = new PropertyPath("(0)", propertyInfo);
var binding = new Binding
{
    Path = propertyPath
};
Run Code Online (Sandbox Code Playgroud)

有关PropertyPath上面传递的语法的详细信息,请参阅PropertyPath.Path.