此代码适用于4.0但在4.5中抛出ApplicationException: Binding.StaticSource cannot be set while using Binding.Source.
:
public class Test
{
public static string Prop { get; set; }
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var binding = new Binding
{
Source = typeof(Test),
Path = new PropertyPath(typeof(Test).GetProperty("Prop")),
Mode = BindingMode.OneWayToSource,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
BindingOperations.SetBinding(textBox1, TextBox.TextProperty, binding);
}
有解决方法吗?目标是以编程方式绑定到静态属性(OneWayToSource),而不实例化Test
。
答案 0 :(得分:3)
Source
中您不需要static bindings
财产。这甚至不会在.Net 4.0中运行。删除Source
属性,它将 -
var binding = new Binding
{
Path = new PropertyPath(typeof(Test).GetProperty("Prop")),
Mode = BindingMode.OneWayToSource,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
BindingOperations.SetBinding(textBox1, TextBox.TextProperty, binding);