2016-04-10 56 views
0

我結合其內容屬性正在嘗試在運行時創建一個標籤,並連接它的Content財產到另一個TextBox控制這是在我的UserControl稱爲MyLabelSettings如何創建標籤,並動態地添加在WPF

這是我走到這一步:

Label currCtrl = new Label(); 
MyLabelSettings currCtrlProperties = new MyLabelSettings(); 

// Bindings to properties 
Binding binding = new Binding(); 
binding.Source = currCtrlProperties.textBox_Text.Text; 
binding.Path = new PropertyPath(Label.VisibilityProperty); 
BindingOperations.SetBinding(currCtrl.Content, Label.ContentProperty, binding); 

最後一行顯示了我也沒弄明白怎麼解決的錯誤:

爲「系統的最佳重載的方法匹配。 Windows.Data.BindingOperations。 SetBinding(System.Windows.DependencyObject,System.Windows.DependencyProperty,System.Windows.Data.BindingBase)」有一些無效參數

我在MyLabelSettingsINotifyPropertyChanged 實施其具有下面的代碼時TexBox.Text變化

private void TextBox_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    InvokePropertyChanged(new PropertyChangedEventArgs("TextChanged")); 
} 

有沒有更好的方法來綁定這2個?或者我在這件事上做錯了什麼?

謝謝!

回答

0

的問題是簡單的比你意識到:

此:

binding.Source = currCtrlProperties.textBox_Text.Text; 
binding.Path = new PropertyPath(Label.VisibilityProperty); 
BindingOperations.SetBinding(currCtrl.Content, Label.ContentProperty, binding); 

應該是這樣的:

//The source must be an object, NOT a property 
binding.Source = currCtrlProperties; 
//Since the binding source is not a DependencyObject, we using string to find it's property 
binding.Path = new PropertyPath("TextToBind"); 
BindingOperations.SetBinding(currCtrl, Label.ContentProperty, binding); 

之前,你試圖通過綁定的值對象的屬性屬性。

注:現在,你通過一個對象(綁定值對象的屬性

  • 您試圖存在於一個類的實例控制文本綁定你剛纔。發

    MyLabelSettings currCtrlProperties = new MyLabelSettings(); 
    

    我基地這個假設過這條線:

    currCtrlProperties.textBox_Text.Text; 
    

    哪個APPE ars包含某種文本控件。相反,您希望綁定存在於您製作的類的實例中的屬性的文本,而不是控件

相關問題