当前位置:首页 > Windows程序 > 正文

C# INotifyPropertyChanged使用方法

2021-03-18 Windows程序

标签:

INotifyPropertyChanged 接口:向客户端发出某一属性值已更改的通知。 NotifyPropertyChanged 接口用于向客户端(通常是执行绑定的客户端)发出某一属性值已更改的通知。

一般使用地方是:加载数据时,及时更新相应的数据加载名称。操作功能时,及时提示相应的错误信息。

实例:

xaml代码:

<TextBlock Margin="80,5,80,0" TextWrapping="Wrap" Foreground="White" FontFamily="微软雅黑" Text="{Binding Message, Mode=TwoWay}" ToolTip="{Binding Message}" TextTrimming="WordEllipsis" Grid.Row="2" FontSize="14"></TextBlock>

后台代码:

private string _message = string.Empty;
/// <summary>
/// 错误消息
/// </summary>
public string Message
{
get { return _message; }
set
{
_message = value;
//使用时用Message才能反应到控件中,直接给_message赋值不能直接反应到控件中
NotifyPropertyChanged("Message");
}
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void NotifyPropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}

消息赋值:

Message = "正在加载数据!";

详细实例(抄袭):

在WPF中进行数据绑定的时候常常会用到INotifyPropertyChanged接口来进行实现,下面来看一个INotifyPropertyChanged的案例。

下面定义一个Person类:

using System;  

using System.Collections.Generic;  

using System.Linq;  

using System.Text;  

using System.ComponentModel;  

  

namespace WpfApp  

{  

    public class Person:INotifyPropertyChanged  

    {  

        private String _name = "张三";  

        private int _age = 24;  

        private String _hobby = "篮球";  

            

        public String Name  

        {  

            set  

            {  

                _name = value;  

                if (PropertyChanged != null)//有改变  

                {  

                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));//对Name进行监听  

                }  

            }  

            get  

            {  

                return _name;  

            }  

        }  

  

        public int Age  

        {  

            set  

            {  

                _age = value;  

                if (PropertyChanged != null)  

                {  

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/63037.html