WPF:无法绑定到自定义 DependencyProperty

WPF: Binding to custom DependencyProperty not possible

我尝试向 DataGridTextColumn 添加自定义数据属性。

我继承了一个自定义 Class 并添加了一个依赖 属性 如下:

public class CustomDataGridTextColumn : DataGridTextColumn
{
    public int MyProperty
    {
        get { return (int)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    // Using a DependencyProperty as the backing store for MyProperty.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(int), typeof(CustomDataGridTextColumn), new PropertyMetadata(0));


}

我在 InitComponents() 之后立即在主窗口构造函数中使用以下代码设置绑定;:

CustomDataGridTextColumn test = new CustomDataGridTextColumn()
{
    Header = "1. Operand",
    Binding = new Binding("Operand1") //<- This works
};

test.SetValue(CustomDataGridTextColumn.MyPropertyProperty, new Binding("Operand1")); // <- This doesn't

启动我的应用程序时,我在 "test.SetValue(...)" 处收到一个 "System.ArgumentExcpetion",说明“"System.Windows.Data.Binding" 不是 属性 "MyProperty" 的有效值”(注意: 这个错误信息是我翻译的,因为没有像"CS1324")这样的错误代码。

就我而言,每个依赖项 属性 都应该支持 DataBindings 吗?

为了在代码隐藏中建立绑定,您必须使用 BindingOperations.SetBinding 方法而不是 SetValue:

BindingOperations.SetBinding(
    test,
    CustomDataGridTextColumn.MyPropertyProperty,
    new Binding("Operand1"));