将标签绑定到“变量” [英] Bind a label to a "variable"
问题描述
我有一个名为label的Label控件。这是我想要完成的:
我想将label.Text的值绑定到变量X.以这种方式,当变量X更改时将被反射回到label.Text。
现在,我不想写事件监听器并与这个代理一起玩(我想要最少的代码)。有没有办法为此使用DataBinding组件?或任何其他新颖的技术?
谢谢,
Ian
如果要使用数据绑定基础架构,并反映对值进行的更改,则需要一种通知用户界面对绑定值所做更改的方法。
所以最好的方式是使用一个属性并实现 INotifyPropertyChanged
界面,如下所示:
class frmFoo:Form,INotifyPropertyChanged
{
private string _foo;
public string Foo
{
get {return _foo; }
set
{
_foo = value;
OnPropertyChanged(Foo);
}
}
protected virtual void OnPropertyChanged(string property)
{
if(PropertyChanged!= null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
#region INotifyPropertyChanged成员
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
还记得你需要首先在标签上设置绑定:
public frmFoo()
{
InitializeComponent();
lblTest.DataBindings.Add(new Binding(Text,this,Foo));
}
Say I have a global variable INT named X. Since X is global, we can assume that anything can modify its value so it is being changed everytime.
Say I have a Label control named "label". Here's what I want to accomplish:
I want to "bind" the value of label.Text to variable X. In such a way that when variable X is changed, it will be reflected back to label.Text.
Now, I don't want to write event listeners and play with delegates with this one (I want the least amount of code as possible). Is there a way to use the DataBinding component for this one? or any other novel techniques?
Thanks, Ian
If you want to use the Databinding infrastructure, and reflect the changes made to a value, you need a way to notify the UI about the changes made to the binding value.
So the best way to do that is to use a property and implement the INotifyPropertyChanged
interface, like this:
class frmFoo : Form, INotifyPropertyChanged
{
private string _foo;
public string Foo
{
get { return _foo; }
set
{
_foo = value;
OnPropertyChanged("Foo");
}
}
protected virtual void OnPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
Also remember that you need to setup the binding on the label first:
public frmFoo()
{
InitializeComponent();
lblTest.DataBindings.Add(new Binding("Text", this, "Foo"));
}
这篇关于将标签绑定到“变量”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!