WPF MVVM框架 - Prism BindableBase 基类介绍和使用

209

Prism是一个用于构建模块化、松耦合的WPF应用程序的框架,而 BindableBase 是其中的一个基类,要用于简化数据绑定和属性变更通知的实现。

作用

BindableBase 是 Prism 提供的基类,实现了 INotifyPropertyChanged 接口,用于在 MVVM 模式中自动通知 UI 层属性的变更。通过继承 BindableBase,ViewModel 中的属性可以轻松触发属性变更事件,无需手动编写样板代码。

核心功能

属性变更通知:当属性的值发生改变时,自动触发 PropertyChanged 事件,通知 UI 更新绑定的控件。

简化代码:通过 SetProperty 方法设置属性值,自动判断新旧值是否相同,避免重复触发事件。

手动触发通知:支持手动调用 RaisePropertyChanged 方法,强制通知 UI 更新。

使用示例

1. 继承 BindableBase

在 ViewModel 中,让类继承 BindableBase:

using Prism.Mvvm;

public class MyViewModel : BindableBase
{
    // 属性定义
}

2. 定义可绑定属性

使用 SetProperty 方法实现属性变更通知:

using Prism.Mvvm;

public class MyViewModel : BindableBase
{
    private string _name;
    public string Name
    {
        get => _name;
        set => SetProperty(ref _name, value); // 自动触发 PropertyChanged
    }
}

SetProperty 方法会检查新旧值是否一致,仅当值变化时触发事件。

无需手动编写 PropertyChanged 事件逻辑。

使用 RaisePropertyChanged 方法手动触发通知

如果需要手动通知 UI(例如计算属性),可以调用 RaisePropertyChanged:

using Prism.Mvvm;

public class MyViewModel : BindableBase
{
      public string _name;
      public string Name
      { 
          get => _name; 
          set {
              _name = value; 
              RaisePropertyChanged(); 
          } 
      }
}

与传统实现对比

在没有 BindableBase 的情况下,需要手动实现 INotifyPropertyChanged

    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;

        public void OnPropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public class MainWindowViewModel : ViewModelBase
    {
        public string? userName;
        public string? UserName { get { return userName; } set { userName = value; OnPropertyChanged(); } }
        
        public string? password;
        public string? Password { get { return password; } set { password = value; OnPropertyChanged(); } }

        private string? message;
        public string? Message { get { return message; } set { message = value; OnPropertyChanged(); } }
    }

注意事项

命名空间:确保引用 Prism.Mvvm。

性能优化:SetProperty 会自动检查值是否变化,避免不必要的 UI 更新。

代码简洁性:避免在属性 setter 中添加复杂逻辑,保持 ViewModel 轻量。