.NET 4.5打破了静态绑定

时间:2013-07-14 08:43:17

标签: c# .net wpf data-binding

此代码适用于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

1 个答案:

答案 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);