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

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

问题描述

假设我有一个名为 X 的全局变量 INT.由于 X 是全局变量,我们可以假设任何东西都可以修改其值,因此每次都会更改.

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.

假设我有一个名为label"的标签控件.这是我想要完成的:

Say I have a Label control named "label". Here's what I want to accomplish:

我想将label.Text的值绑定"到变量X上,这样当变量X发生变化时,它会反映回label.Text.

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.

现在,我不想编写事件侦听器并与委托一起玩这个(我想要尽可能少的代码).有没有办法为此使用 DataBinding 组件?或者其他什么新技术?

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?

推荐答案

如果您想使用数据绑定基础结构,并反映对值所做的更改,您需要一种方法来通知 UI 对绑定所做的更改价值.

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.

因此,最好的方法是使用属性并实现 INotifyPropertyChanged 接口,如下所示:

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天全站免登陆