绑定属性来控制的WinForms [英] Binding property to control in Winforms
问题描述
所以,当属性值发生变化时,它控制的绑定属性改变什么是一个属性绑定到一个控制的最佳途径。
What is the best way to bind a property to a control so that when the property value is changed, the control's bound property changes with it.
所以,如果我有一个属性姓
我要绑定到一个文本框的 txtFirstName
文本值。所以,如果我改变姓
价值堆栈,那么属性 txtFirstName.Text
也变成值堆栈。
So if I have a property FirstName
which I want to bind to a textbox's txtFirstName
text value. So if I change FirstName
to value "Stack" then the property txtFirstName.Text
also changes to value "Stack".
我知道这听起来可能愚蠢的问题,但我会AP preciate的帮助。
I know this may sound a stupid question but I'll appreciate the help.
推荐答案
您必须实施 INotifyPropertyChanged的
键,添加绑定到文本框。
You must implement INotifyPropertyChanged
And add binding to textbox.
我公司将提供C#code片段。希望它能帮助
I will provide C# code snippet. Hope it helps
class Sample : INotifyPropertyChanged
{
private string firstName;
public string FirstName
{
get { return firstName; }
set
{
firstName = value;
InvokePropertyChanged(new PropertyChangedEventArgs("FirstName"));
}
}
#region Implementation of INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
public void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, e);
}
#endregion
}
用法:
Sample sourceObject = new Sample();
textbox.DataBindings.Add("Text",sourceObject,"FirstName");
sourceObject.FirstName = "Stack";
这篇关于绑定属性来控制的WinForms的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!