C#的MVVM架构中的几种数据绑定方式

C#的MVVM架构中几种前端数据绑定方式

WPF基础框架

通过继承接口INotifyPropertyChangedICommand 来实现。

数据绑定部分

INotifyPropertyChanged原代码如下,WPF框架会自动注册DataContext对象中的PropertyChanged事件(若事件存在)。然后根据该事件修改前端属性。

csharp 复制代码
namespace System.ComponentModel
{
    // Notifies clients that a property value has changed.
    public interface INotifyPropertyChanged
    {
        // Occurs when a property value changes.
        event PropertyChangedEventHandler? PropertyChanged;
    }
}

注意:INotifyPropertyChanged接口并非是强制要求的,当不需要通过设置属性自动修改页面数据时,也就是不需要执行set方法时,不需要继承该接口。若使用了通知集合ObservableCollection,也是不需要专门通过事件通知页面的。

csharp 复制代码
public class NativeViewModel : INotifyPropertyChanged
{
    private string _name;

    public string Name
    {
        get => _name;
        set
        {
            if (_name != value)
            {
                _name = value;
                OnPropertyChanged();
            }
        }
    }
    protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}
xml 复制代码
<StackPanel>
    <TextBox Text="{Binding Name}" />
</StackPanel>

数据绑定中的命令绑定

ICommand 原代码如下,可以看到其中有按钮操作常用的几种属性:是否可用、可用性变化、触发事件。与前端通过Click属性指定事件相比:一个是前端指定要执行的逻辑,一个是由vm来确定最终的执行逻辑,相当于是反转了控制方。可以根据需要使用、并非强制要求。

csharp 复制代码
#nullable enable

using System.ComponentModel;
using System.Windows.Markup;

namespace System.Windows.Input
{
    //
    // 摘要:
    //     Defines a command.
    [TypeConverter("System.Windows.Input.CommandConverter, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
    [ValueSerializer("System.Windows.Input.CommandValueSerializer, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, Custom=null")]
    public interface ICommand
    {
        //
        // 摘要:
        //     Occurs when changes occur that affect whether or not the command should execute.
        event EventHandler? CanExecuteChanged;

        //
        // 摘要:
        //     Defines the method that determines whether the command can execute in its current
        //     state.
        //
        // 参数:
        //   parameter:
        //     Data used by the command. If the command does not require data to be passed,
        //     this object can be set to null.
        //
        // 返回结果:
        //     true if this command can be executed; otherwise, false.
        bool CanExecute(object? parameter);
        //
        // 摘要:
        //     Defines the method to be called when the command is invoked.
        //
        // 参数:
        //   parameter:
        //     Data used by the command. If the command does not require data to be passed,
        //     this object can be set to null.
        void Execute(object? parameter);
    }
}

对于ICommand属性,推荐使用方式是不要让其触发PropertyChanged,不应该被动态设置,而应该初始定好。不过如果使用场景确实需要,应该也是能生效的。

csharp 复制代码
public class NativeViewModel
{
    public ICommand GreetCommand { get; }

    public NativeViewModel()
    {
        // 使用自定义的 RelayCommand 需要自己实现
        GreetCommand = new RelayCommand();
    }
}

// 需要实现的简单命令类
public class RelayCommand : ICommand
{
    // 略
}
xml 复制代码
<StackPanel>
    <Button Content="Say Hello" Command="{Binding GreetCommand}" />
</StackPanel>

CommunityToolkit.Mvvm 方式

CommunityToolkit.Mvvm 利用 C# 的源码生成器,在编译时自动生成INotifyPropertyChangedICommand的样板代码。需要nuget包CommunityToolkit.Mvvm

其仅在vm上有区别,在实际绑定方式上没有区别。

csharp 复制代码
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;

// 3. 使用 [ObservableObject] 特性或继承 ObservableObject
[ObservableObject]
public partial class ToolkitViewModel
{
    // 4. 使用 [ObservableProperty] 标记字段,自动生成名为 "Name" 的属性
    [ObservableProperty]
    [NotifyCanExecuteChangedFor(nameof(GreetCommand))] // 当 Name 改变时,通知 GreetCommand 重新验证
    private string _name;

    [ObservableProperty]
    private string _greeting;

    // 5. 使用 [RelayCommand] 自动生成名为 GreetCommand 的 ICommand 属性
    [RelayCommand(CanExecute = nameof(CanGreet))]
    private void Greet()
    {
        Greeting = $"Hello from Toolkit, {Name}!";
    }

    private bool CanGreet() => !string.IsNullOrWhiteSpace(Name);
}

ReactiveUI

ReactiveUI 将响应式编程理念引入 MVVM,核心是使用ReactiveObjectWhenAnyValue等来声明数据流和反应关系。需要nuget包ReactiveUI.WPF

其仅在vm上有区别,在实际绑定方式上没有区别。

csharp 复制代码
using ReactiveUI;
using System.Reactive.Linq;

// 6. 继承 ReactiveObject
public class ReactiveViewModel : ReactiveObject
{
    // 7. 使用 [Reactive] 特性或 WhenAnyValue
    private string _name;
    public string Name
    {
        get => _name;
        set => this.RaiseAndSetIfChanged(ref _name, value);
    }

    private readonly ObservableAsPropertyHelper<string> _greeting;
    public string Greeting => _greeting.Value;

    // 8. 使用 ReactiveCommand 创建命令
    public ReactiveCommand<Unit, Unit> GreetCommand { get; }

    public ReactiveViewModel()
    {
        // 判断命令何时可执行:当 Name 不为空时
        var canGreet = this.WhenAnyValue(x => x.Name, name => !string.IsNullOrWhiteSpace(name));

        // 创建命令
        GreetCommand = ReactiveCommand.CreateFromTask(
            execute: async () => { /* 可以执行异步操作 */ return $"Hello from ReactiveUI, {Name}!"; },
            canExecute: canGreet // 绑定可执行条件
        );

        // 9. 将命令的执行结果(一个IObservable<string>)订阅到 Greeting 属性
        _greeting = GreetCommand.ToProperty(this, x => x.Greeting, initialValue: "Waiting...");

        // 另一种更直接的写法(不通过命令结果):
        // GreetCommand = ReactiveCommand.Create(() => { Greeting = $"Hello from ReactiveUI, {Name}!"; }, canGreet);
        // 但上面那种方式展示了将 IObservable 流转换为属性的强大能力。
    }
}
相关推荐
武藤一雄25 分钟前
.NET 中常见计时器大全
microsoft·微软·c#·.net·wpf·.netcore
MarkHD4 小时前
车辆TBOX科普 第70次 AUTOSAR Adaptive、容器化与云原生的融合革命
云原生·wpf
极客智造5 小时前
WPF Behavior 实战:自定义 InvokeCommandAction 实现事件与命令解耦
wpf
L、2185 小时前
Flutter 与 OpenHarmony 深度集成:构建分布式多端协同应用
分布式·flutter·wpf
布伦鸽5 小时前
C# WPF -MaterialDesignTheme 找不到资源“xxx“问题记录
开发语言·c#·wpf
小二·17 小时前
MyBatis基础入门《十五》分布式事务实战:Seata + MyBatis 实现跨服务数据一致性
分布式·wpf·mybatis
helloworddm1 天前
UnregisterManyAsync
wpf
军训猫猫头1 天前
3.NModbus4 长距离多设备超时 C# + WPF 完整示例
c#·.net·wpf·modbus
Aevget1 天前
DevExpress WPF中文教程:Data Grid - 如何绑定到有限制的自定义服务(一)?
ui·.net·wpf·devexpress·ui开发·wpf界面控件
Macbethad1 天前
半导体设备工厂自动化软件技术方案
wpf·智能硬件