2017-05-08 78 views
0

我尝试将自定义DataProperty添加到DataGridTextColumn。WPF:绑定到自定义DependencyProperty不可能

心中已经继承了一个自定义类,并添加一个依赖属性如下:

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 
之后

当开始我的申请,我得到一个“System.ArgumentExcpetion”在“test.SetValue(...)”,指出“” System.Windows.Data.Binding“不是属性‘myProperty的’”(注有效值:此错误消息由我翻译,因为没有像“CS1324”这样的错误代码)。

至于我关注每一个依赖项属性应该支持数据绑定?

+0

我忘了提及,这必须在代码来完成后面。 –

回答

2

为了建立在代码中绑定的背后,你必须使用BindingOperations.SetBinding方法而不是SetValue

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

Unfortunality存在用于DataGridTextColumn –

+0

见编辑没有SetBinding的方法,自FrameworkElement派生类提供为方便起见,[SetBinding](https://msdn.microsoft.com/en-us/library/ms598270.aspx)方法。 – Clemens

+0

这适用于我现在。谢谢你,祝你有美好的一天。 –

相关问题