2017-05-08 79 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

這適用於我現在。謝謝你,祝你有美好的一天。 –

相關問題