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

C# 如何在WPF中创建标签并向其内容属性动态添加绑定,c#,wpf,wpf-controls,C#,Wpf,Wpf Controls,我试图在运行时创建一个标签,并将它的内容属性连接到另一个文本框控件,该控件位于我的用户控件中,名为MyLabelSettings 到目前为止,我得到的是: Label currCtrl = new Label(); MyLabelSettings currCtrlProperties = new MyLabelSettings(); // Bindings to properties Binding binding = new Binding(); binding.Source = currC

我试图在运行时创建一个标签,并将它的
内容
属性连接到另一个
文本框
控件,该控件位于我的
用户控件
中,名为
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"));
}
有没有更好的方法来绑定这2个?还是我在这件事上做错了什么


谢谢

问题比您意识到的要简单:

这:

应该是这样的:

//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;
    
    它似乎包含某种类型的文本控件。相反,您希望绑定存在于所创建类的实例中的属性的文本,而不是控件

currCtrlProperties.textBox_Text.Text;