我正在尝试在运行时创建标签,并将其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"));
}
有没有更好的方法来绑定这两个?还是我在这件事上做错了什么?
谢谢!
这个问题比您意识到的要简单:
这:
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;
其中似乎包含某种文本控件。而是要绑定在您所创建的类的实例中存在的属性的文本,而不是控件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句