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

How to create label and dynamically add binding to its content property in WPF

我正在尝试在运行时创建一个标签并将其 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);

最后一行显示了一个我不知道如何解决的错误:

The best overloaded method match for 'System.Windows.Data.BindingOperations. SetBinding(System.Windows.DependencyObject, System.Windows.DependencyProperty, System.Windows.Data.BindingBase)' has some invalid arguments

我已经在MyLabelSettings执行了INotifyPropertyChangedTexBox.Text 更改

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

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

谢谢!

问题比你想象的要简单:

这个:

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

之前,您试图通过 属性 将值绑定到对象的 属性。现在,您通过对象 (:

将值绑定到对象的 属性

备注:

  • 您正试图绑定存在于您刚创建的 class 实例中的控件的文本。

    MyLabelSettings currCtrlProperties = new MyLabelSettings();
    

    我根据这条线做出这个假设:

    currCtrlProperties.textBox_Text.Text;
    

    其中似乎包含某种文本控件。相反,您想要绑定 属性 的文本,它存在于您创建的 class 实例中,而不是 control.