将标签绑定到“变量” [英] Bind a label to a "variable"

查看:98
本文介绍了将标签绑定到“变量”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个名为X的全局变量INT。由于X是全局的,我们可以假设任何东西都可以修改它的值,所以每次都被改变。



我有一个名为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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆