WPF中 INotifyPropertyChanged

在Windows Presentation Foundation (WPF)中,INotifyPropertyChanged 是一个核心接口,用于实现实体类与视图之间的数据双向绑定 。当实体类的某个属性值 发生变化时,通过实现此接口可以立即通知绑定到该属性的所有 UI 控件进行更新,ICommand主要针对的是关联到任何实现了 ICommand 接口的对象的方法。

在C#中,CallerMemberName 是.NET框架提供的一个编译器特性(Compiler Feature),它允许你获取调用当前方法的成员名称,而无需硬编码该名称。这对于实现INotifyPropertyChanged接口特别有用,因为它可以减少手动输入属性名的工作量,提高代码的健壮性和可维护性。

不管是ICommand还是INotifyPropertyChanged 都必须首先将ViewMode的实例设置为控件或整个界面的 DataContext如,this.DataContext = new MainViewModel();DataContext是UI层与数据逻辑层的桥梁。

DataContext作为一个容器,提供了UI层和数据层之间的连接点。在MVVM(Model-View-ViewModel)架构模式中,通常将 ViewModel 设置为控件或整个界面的 DataContext,这样 UI 控件可以通过绑定直接访问 ViewModel 中的数据和命令。

例如,在上面的INotifyPropertyChanged实现中,我们可以使用CallerMemberName特性来简化OnPropertyChanged方法的调用:

cs 复制代码
1using System.ComponentModel;
2using System.Runtime.CompilerServices;
3
4public class MyViewModel : INotifyPropertyChanged
5{
6    // ...
7
8    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = "")
9    {
10        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
11    }
12}
13
14public string MyProperty
15{
16    get { return myPropertyBackingField; }
17    set
18    {
19        if (myPropertyBackingField != value)
20        {
21            myPropertyBackingField = value;
22            OnPropertyChanged(); // 这里不再需要传入 "MyProperty"
23        }
24    }
25}

在此版本中,当你调用OnPropertyChanged()时,编译器会自动填充propertyName参数,将其设为调用方法的成员名称,即"MyProperty"。这样,当MyProperty的值改变时,绑定系统能够准确地知道哪个属性发生了变化并作出相应的更新。

cs 复制代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace WpfApplication1
{
    public class MyNotifyProperyChanged : INotifyPropertyChanged //主要通过实现INotifyPropertyChanged接口,实现UI和属性绑定
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public void OnPropertyChanged([CallerMemberName] string propertyname ="")//属性值变化调用事件,属性特性要调用的属性值给propertyname
        {
            PropertyChanged?.Invoke(this,new PropertyChangedEventArgs(propertyname));
        }

    }
}
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApplication1
{
    public class MainViewModel : MyNotifyProperyChanged
    {
        public MyCommand MyCommandOrder { get; set; }

        private string _name;
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged();//调用基类事件
            }
        }

        private string _tittle;

        public string Tittle
        {
            get { return _tittle; }
            set { _tittle = value; OnPropertyChanged(); }
        }
        public MainViewModel()
        {
            MyCommandOrder = new MyCommand(ShowMessage);
        }

        public void ShowMessage()
        {
            Name = "点击了按钮";
            Tittle = "我是标题";
            MessageBox.Show(Name);
        }
    }
}
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
    }
}
XML 复制代码
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <TextBox  Text="{Binding Name}"> </TextBox>
            <TextBox  Text="{Binding Tittle}" ></TextBox>
            <Button Content="按钮" Command="{Binding MyCommandOrder}"></Button> <!--  Command命令绑定,绑定的也是一个属性,需要指定数据源,实现ICommand接口 -->
        </StackPanel>
    </Grid>
</Window>
相关推荐
YrqnxehxDo3 小时前
相场模拟——合金,金属凝固模型,各向异性枝晶生长karma 合金凝固模型,选区激光熔融,激光增...
wpf
竟未曾年少轻狂1 天前
Spring Boot 项目集成 Redis
java·spring boot·redis·缓存·消息队列·wpf·redis集群
清风~徐~来1 天前
【视频点播系统】Redis-SDK 介绍及使用
数据库·redis·wpf
棉晗榜1 天前
WPF DataGrid鼠标滚不动,划不动解决
wpf
baivfhpwxf20231 天前
wpf自适应布局
wpf
艺杯羹2 天前
Git版本控制深度复盘:从入门到精通的完整指南
git·wpf·版本控制·git学习·git复盘
玄〤2 天前
RabbitMQ 入门篇总结(黑马微服务课day10)(包含黑马商城业务改造)
java·笔记·分布式·spring cloud·微服务·rabbitmq·wpf
向哆哆3 天前
CANN HCCL集合通信库在分布式训练中的高性能通信方案
分布式·wpf·cann
周杰伦fans3 天前
ai-skill开发WPF踩坑
wpf
听麟3 天前
HarmonyOS 6.0+ APP智能快递代收管理系统开发实战:定位追踪与取件提醒落地
深度学习·3d·华为·wpf·harmonyos