WPF入门第五篇 界面绑定属性刷新

界面绑定属性刷新

新建WPF项目,命名为VMTest(VM是ViewModel的简称)。右击项目添加一个类,命名为Person。将Person类进行修改:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VMTest
{
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

将MainWindow.xaml代码替换为下面代码:

<Window x:Class="VMTest.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:VMTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
  <Grid>
    <StackPanel Orientation="Vertical">
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="Id:"></TextBlock>
        <TextBlock Text="{Binding Id}"></TextBlock>
      </StackPanel>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="Name:"></TextBlock>
        <TextBlock Text="{Binding Name}"></TextBlock>
      </StackPanel>
      <StackPanel Orientation="Horizontal">
        <TextBlock Text="Age:"></TextBlock>
        <TextBlock Text="{Binding Age}"></TextBlock>
      </StackPanel>
      <StackPanel Orientation="Vertical">
        <Button Content="btn1" Width="100" HorizontalAlignment="Left" Click="Button_Click"></Button>
      </StackPanel>
    </StackPanel>
  </Grid>
</Window>

将MainWindow.xaml.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 VMTest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Person p;
        public MainWindow()
        {
            InitializeComponent();
            p = new Person()
            {
                Id = 1,
                Name = "Wufan",
                Age = 25
            };
            this.DataContext = p;
        }
        private void Button_Click(object sender,RoutedEventArgs e)
        {
            p.Age = 26;
        }
    }
}

测试项目简单的准备完毕了,分析一下代码:

MainWindow作为View,被它内部定义的Person p控制着显示的数据,在MainWindow的初始化代码中,我们new了一个Person赋值给p,并设置MainWindow的DataContext等于p。在MainWindow的ButtonClick事件中,我们改变了p.Age的值,期望界面上绑定值也能随着绑定模型的属性的变化而变化。
此时运行程序,可以看到界面显示了Person的三个属性值,但是点击btn1时,Age却没有随着变化,未达到我们的预期。

为了解决这个问题,最笨的方法就是对DataContext重新赋值,来刷新整个界面的所有Binding值。这种方法的具体做法是将ButtonClick代码改为:

private void Button_Click(object sender, RoutedEventArgs e)
{
    p.Age = 26;
    Person temp = new Person()
    {
        Id = p.Id,
        Name = p.Name,
        Age = p.Age
    };
    this.DataContext = temp;
    p = temp;
}

这样做确实可以解决问题,但却不是一个好的方法。因为重新给DataContext复制后,界面的所有Binding值都要刷新,这不符合我们的开发要求,也不符合设计者的初衷。
为了避免这种方法,设计者提供了INotifyPropertyChanged。

  • INotifyPropertyChanged的作用和用法
    对于INotifyPropertyChanged的作用说明:向客户端发出某一属性值已更改的通知。简单来说,可以在不给DataContext重新赋值的情况下,界面Binding值可以随着绑定模型的属性的变化而变化。
    将ButtonClick按钮的代码改为:
private void Button_Click(object sender, RoutedEventArgs e)
{
    p.Age = 26;
}

为Person类添加接口继承,并添加相应的引用及接口实现;修改Age属性的实现方式,并使用PropertyChanged来将Age属性的改变通知到界面:

using System;
using System.Collections.Generic;
using System.ComponentModel;//新增的引用
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VMTest
{
    public class Person:INotifyPropertyChanged
    {
        public int Id { get; set; }
        public string Name { get; set; }
        //Age属性的改变
        private int _age;
        public int Age 
        { 
            get => _age; 
            set
            {
                _age = value;
                if(PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));
                }
            }
        }

        //新增代码
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

此时,点击btn1后,Age属性的改变被通知到了界面。
为了让Id和Name属性也能实现这种效果,则需要将这两个属性的写法也改成上面介绍的Age属性的写法。

如果直接修改会让我们的代码非常繁琐,我们可以将INotifyPropertyChanged相关代码封装起来使用,使得ViewModel(本文中的Person类)的代码看起来更加简洁。

  • INotifyPropertyChanged的封装使用
    我们对INotifyPropertyChanged做一个封装,封装到VM类,其他的ViewModel类只需要继承VM类,即可方便的实现属性变更通知的效果。

在项目中添加一个类,命名为VM。VM类代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace VMTest
{
    public class VM : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string p)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(p));
            }
        }
        public void RaiseAndSetIfChanged<T>(ref T a, T v, [CallerMemberName] string propertyName = null)
        {
            a = v;
            if (propertyName != null)
            {
                RaisePropertyChanged(propertyName);
            }
        }
    }
}

将Person类代码替换为下面的代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace VMTest
{
    public class Person : VM
    {

        private int _id;
        public int Id
        {
            get => _id;
            set => this.RaiseAndSetIfChanged(ref _id, value);//说明:这里没有把方法定义时的第三个参数也放进来,原因是:系统特性。
                                                            //因为[CallerMemberName]这样的特性,系统会自动帮你获取到调用堆栈的对象名称。
                                                            //所以这里的代码等价于:
                                                            // set => this.RaiseAndSetIfChanged(ref _id, value,"Id");
        }

        private string _name;
        public string Name
        {
            get => _name;
            set => this.RaiseAndSetIfChanged(ref _name, value);//同理
        }

        private int _age;
        public int Age
        {
            get => _age;
            set => this.RaiseAndSetIfChanged(ref _age, value);//同理
        }

    }
}

此时,Id、Name、Age属性的改变都可以被通知到界面。
修改Button按钮的点击事件如下:

private void Button_Click(object sender, RoutedEventArgs e)
{
    p.Age = 26;
    p.Name = "wf";
    p.Id = 2;
}

到此为止,代码已经可以实现预期的效果了。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值