C#:当对象的字段值发生变化时创建一个事件
有没有办法创建一个在对象的属性/字段值更改时触发的事件?例如,如果该对象有一个名为“?”的字段
private int number;
,并且用户执行将更新该数字的操作,则将触发一个事件,该事件将更新表单上的所有文本框以显示当前字段值?
编辑: 抱歉,是的,已为每个字段创建了属性。
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?
EDIT:
Sorry, yes properties have been created for each field.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使其成为属性而不是字段,并在类中实现
INotifyPropertyChanged
:然后您可以显式侦听
PropertyChanged
事件,或使用自动处理该事件的数据绑定Make it a property rather than a field, and implement
INotifyPropertyChanged
in your class :You can then listen explicitly for the
PropertyChanged
event, or use a data binding that will handle it automatically您应该使用用户定义的 getter 和 setter(即属性)来手动触发事件。看看这段代码,应该很简单:
我们的成员变量被定义为私有的,所以Widget类之外的任何人都无法访问它;他们被迫使用属性 Widget_X,一旦使用,就会出现两种情况:
x
变量。无事可做。x
变量设置为之前的相同值。无事可做。我们在设置器内检查它。x
变量。这就是我们触发事件的地方。在调用事件之前,检查是否注册了任何事件处理程序(即我们的事件不为空)至关重要。在其他情况下,我们会得到一个例外。
You should use user-defined getters and setters (i.e. properties) to manually fire the event. Look at this code, it should be pretty simple:
Our member variable is defined private, so no one outside of the class Widget can access it; they are forced to use the property Widget_X, and once they do, there are two cases:
x
variable. Nothing to do.x
variable to the same value it had before. Nothing to do. We check it inside the setter.x
variable and change it. That is where we fire the event.It is critical to check if we have any event handlers registered (that is, our event is not null) before we ever invoke the event. In other case, we'll get an exception.
听起来您应该查看 INotifyPropertyChanged 界面。但它不适用于字段,您必须手动实现它。
Sounds like you should check out the INotifyPropertyChanged interface. It doesn't work for fields though, and you'll have to implement it manually.
你要在哪里使用这个?
如果您要在客户端应用程序中使用它,则实现 INotifyPropertyChanged是推荐的工作方式。
Where are you going to use this?
If you're going to use this in a client application then implementing INotifyPropertyChanged is the recommended way of working.