1

此代码在 4.0 中有效,但ApplicationException: Binding.StaticSource cannot be set while using Binding.Source.在 4.5 中抛出:

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.

4

1 回答 1

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);
于 2013-07-14T08:57:20.450 回答