我尝试将自定义DataProperty添加到DataGridTextColumn。
我继承了一个自定义类并添加了一个依赖属性,如下所示:
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();之后,我在MainWindow构造函数中使用以下代码设置Binding:
CustomDataGridTextColumn test = new CustomDataGridTextColumn()
{
Header = "1. Operand",
Binding = new Binding("Operand1") //<- This works
};
test.SetValue(CustomDataGridTextColumn.MyPropertyProperty, new Binding("Operand1")); // <- This doesn't
启动我的应用程序时,我得到一个&#34; System.ArgumentExcpetion&#34; at&#34; test.SetValue(...)&#34;陈述&#34;&#34; System.Windows.Data.Binding&#34;不属于该物业的有效价值&#34; MyProperty&#34;&#34; (注意:此错误消息由我翻译,因为没有错误代码,如&#34; CS1324&#34;)。
就我而言,每个依赖属性应该支持DataBindings吗?
答案 0 :(得分:2)
为了在代码中建立绑定,您必须使用BindingOperations.SetBinding
方法而不是SetValue
:
BindingOperations.SetBinding(
test,
CustomDataGridTextColumn.MyPropertyProperty,
new Binding("Operand1"));