使用Windows窗体设计器将属性绑定到控件
本文关键字:属性 绑定 控件 Windows 窗体 使用 | 更新日期: 2023-09-27 17:58:12
我想使用Windows窗体设计器将属性绑定到控件。
例如,我有一个组件:
class MyComponent:Component, INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
private string _strProperty;
[Bindable(true)]
public string StrProperty {
get{
return _strProperty;
}
set {
if (_strProperty != value) {
_strProperty = value;
if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("StrProperty"));
}
}
}
}
我从工具箱中拖动这个组件并将其放到窗体上。组件名称为myComponent1。在同一个表单上,我有一个名为textBox1的TextBox控件。
现在我想将textBox1.Text属性绑定到myComponent1.StrProperty的属性。我知道我可以用代码写:
textBox1.DataBindings.Add(new Binding("Text", myComponent1, "StrProperty"));
但我想使用设计器来实现相同的结果。有可能吗?我应该使用BindingSource吗?
由于您的问题已经存在3年了,我不确定这在当时是否适用于您的Visual Studio版本,但对于现在感兴趣的其他人来说,以下是您可以做到的方法:
- 选择textBox1
- 在属性网格中展开(DataBindings)
- 在文本中,输入myComponent1-StrProperty
- 按输入,完成
就这么简单。如果检查生成的设计器代码,您将看到创建的新绑定与代码一样。
否,只能使用WinForm中的代码隐藏绑定属性。但是,您可以在没有C#代码但使用XAML的WPF中绑定数据。