我正在尝试从代码隐藏设置绑定到显式实现的接口属性。代码隐藏绑定的原因是绑定属性的路径只能在运行时确定。
在XAML中,可以这样绑定(MainWindow.xaml中的示例):
<TextBox Text="{Binding (local:IViewModel.Property)}"/>
实际上,后面的代码中的绑定以类似的方式工作(来自MainWindow.xaml.cs):
var binding = new Binding("(local:IViewModel.Property)");
因为WPF能够获取命名空间映射。
我的问题是,当命名空间映射不存在时(例如,在附加行为中),如何形成这样的绑定?
非常感谢提前!
答案 0 :(得分:9)
您可以指定一个完整的PropertyPath
:
var propertyInfo = typeof(IViewModel).GetProperty("Property");
var propertyPath = new PropertyPath("(0)", propertyInfo);
var binding = new Binding
{
Path = propertyPath
};
有关上面传递给PropertyPath
的语法的详细信息,请参阅PropertyPath.Path
。