INotifyPropertyChanged WPF [英] INotifyPropertyChanged WPF

查看:71
本文介绍了INotifyPropertyChanged WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

INotifyPropertyChanged的用途是什么.我知道每当更改属性时都会触发此事件,但是View/UI如何知道触发了此事件:

What is the purpose of INotifyPropertyChanged. I know this event is fired whenever a property is changed but how can the View/UI knows that this event is fired:

这是实现INotifyPropertyChanged事件的我的Customer类:

Here is my Customer class that implements the INotifyPropertyChanged event:

public class Customer : INotifyPropertyChanged
    {
        private string _firstName;

        public string LastName { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;

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

        }

        public string FirstName
        {
            get { return _firstName; }

            set
            {
                _firstName = value;
                OnPropertyChanged("FirstName");
            }
        }
    }

但是现在如何通知UI属性已更改.就像用户为名字分配null或空一样,如何在UI上显示MessageBox.

But now how to notify the UI that property has changed. Like when the user assigns null or empty to the first name how can I display a MessageBox on the UI.

推荐答案

INotifyPropertyChanged允许WPF UI元素(通过标准数据绑定机制)订阅PropertyChanged事件并自动更新自身.例如,如果您有一个TextBlock显示您的FirstName属性,则可以使用INotifyPropertyChanged将其显示在窗体上,当FirstName属性在代码中更改时,它将自动保持最新.

INotifyPropertyChanged allows WPF UI elements (via the standard data binding mechanisms) to subscribe to the PropertyChanged event and automatically update themselves. For example, if you had a TextBlock displaying your FirstName property, by using INotifyPropertyChanged, you can display it on a form, and it will automatically stay up to date when the FirstName property is changed in code.

视图仅订阅该事件-告诉它所有必要的信息.该事件包含更改后的属性的名称,因此,如果UI元素绑定到该属性,它将进行更新.

The View just subscribes to the event - which tells it everything necessary. The event includes the name of the changed property, so if a UI element is bound to that property, it updates.

这篇关于INotifyPropertyChanged WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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