c#:创建一个事件,当对象的字段值更改时 [英] c#: create an event for when an object's field values change

查看:57
本文介绍了c#:创建一个事件,当对象的字段值更改时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种创建事件的方法,该事件将在对象的属性/字段值更改时触发?例如,如果对象具有一个名为

Is there a way to create an event that will fire when an object's attributes/field values change? For instance, if the object has a field called

private int number;

然后用户执行了一个操作,该操作将更新该数字,将触发一个事件,该事件将更新表单上的所有文本框以显示当前字段值?

And the user performs an action that would update that number, an event would fire that would update all of the text boxes on the form to display current field values?

抱歉,已经为每个字段创建了属性.

Sorry, yes properties have been created for each field.

推荐答案

将其设为属性而不是字段,并在您的课程中实现 INotifyPropertyChanged :

Make it a property rather than a field, and implement INotifyPropertyChanged in your class :

class YourClass : INotifyPropertyChanged
{

    private int _number;
    public int Number
    {
        get { return _number; }
        private set
        {
            _number = value;
            OnPropertyChanged("Number");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }

}

然后您可以显式侦听 PropertyChanged 事件,或使用将自动处理该事件的数据绑定

You can then listen explicitly for the PropertyChanged event, or use a data binding that will handle it automatically

这篇关于c#:创建一个事件,当对象的字段值更改时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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