You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Prism的SetProperty实现Person类的PropertyChanged属性绑定

基于Prism实现Person模型与ViewModel的PropertyChanged

没问题,这就帮你完成完整的Prism风格PropertyChanged实现,分为Person模型改造和ViewModel中Person属性实现两部分:

1. 改造Person模型实现属性变更通知

首先让Person类继承Prism的BindableBase(它已经封装了INotifyPropertyChanged接口的实现),然后用SetProperty方法替换自动属性,确保每个属性变更时都会自动触发UI更新通知:

using Prism.Mvvm;
using System;

public class Person : BindableBase
{
    private string _firstName;
    public string FirstName
    {
        get => _firstName;
        set => SetProperty(ref _firstName, value);
    }

    private DateTime _lastUpdated;
    public DateTime LastUpdated
    {
        get => _lastUpdated;
        set => SetProperty(ref _lastUpdated, value);
    }
}

2. 补全ViewModel中的Person属性实现

你的ViewModel需要同样继承BindableBase,然后补全Person属性的setter逻辑,用SetProperty触发整个Person对象替换时的变更通知:

using Prism.Mvvm;

public class YourViewModel : BindableBase
{
    private Person _person;
    public Person Person
    {
        get => _person;
        set => SetProperty(ref _person, value);
    }

    // 建议在构造函数中初始化Person对象,避免视图绑定空引用
    public YourViewModel()
    {
        Person = new Person { FirstName = "默认名称", LastUpdated = DateTime.Now };
    }
}

关键说明

  • 继承BindableBase省去了手动编写INotifyPropertyChanged事件、触发逻辑的冗余代码
  • SetProperty方法会自动对比新旧值,只有当值真正变化时才触发PropertyChanged事件,避免无效的UI刷新
  • 视图中绑定的Person.FirstName既会响应FirstName属性的变更,也会响应Person对象本身的替换

内容的提问来源于stack exchange,提问作者karollo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:04:16