如何在WPF中创建标签并动态添加绑定到其内容属性

时间:2016-04-10 16:32:59

标签: c# wpf wpf-controls

我正在尝试在运行时创建标签,并将其Content属性连接到我TextBox中名为UserControl的另一个MyLabelSettings控件。

这是我到目前为止所得到的:

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);

最后一行显示错误,我没有弄清楚如何解决:

  

'System.Windows.Data.BindingOperations的最佳重载方法匹配。 SetBinding(System.Windows.DependencyObject,System.Windows.DependencyProperty,System.Windows.Data.BindingBase)'有一些无效的参数

我在MyLabelSettings INotifyPropertyChanged的实施 当TexBox.Text更改

时,其代码如下
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
    InvokePropertyChanged(new PropertyChangedEventArgs("TextChanged"));
}

有没有更好的方法来绑定这两个?或者我在这个做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:1)

问题比你意识到的更简单:

此:

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;
    

    其中似乎包含某种文本控件。相反,您希望绑定存在于您所创建的类的实例中的属性的文本,而不是控件