当前位置: 首页 > news >正文

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

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

WPF基础框架

通过继承接口INotifyPropertyChangedICommand 来实现。

数据绑定部分

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

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,也是不需要专门通过事件通知页面的。

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));}
}
<StackPanel><TextBox Text="{Binding Name}" />
</StackPanel>

数据绑定中的命令绑定

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

#nullable enableusing 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,不应该被动态设置,而应该初始定好。不过如果使用场景确实需要,应该也是能生效的。

public class NativeViewModel
{public ICommand GreetCommand { get; }public NativeViewModel(){// 使用自定义的 RelayCommand 需要自己实现GreetCommand = new RelayCommand();}
}// 需要实现的简单命令类
public class RelayCommand : ICommand
{// 略
}
<StackPanel><Button Content="Say Hello" Command="{Binding GreetCommand}" />
</StackPanel>

CommunityToolkit.Mvvm 方式

CommunityToolkit.Mvvm 利用 C# 的源码生成器,在编译时自动生成INotifyPropertyChangedICommand的样板代码。需要nuget包CommunityToolkit.Mvvm
其仅在vm上有区别,在实际绑定方式上没有区别。

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上有区别,在实际绑定方式上没有区别。

using ReactiveUI;
using System.Reactive.Linq;// 6. 继承 ReactiveObject
public class ReactiveViewModel : ReactiveObject
{// 7. 使用 [Reactive] 特性或 WhenAnyValueprivate 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 流转换为属性的强大能力。}
}
http://www.dtcms.com/a/398363.html

相关文章:

  • Jmeter接口测试:jmeter组件元件介绍,利用取样器中http发送请求
  • Apache Tomcat 部署与配置
  • 网站建设详细合同范本西部数码网站管理助手破解版
  • 权限提升专项训练靶场:hacksudo: L.P.E.
  • 工作笔记----lwip的数据管理结构pbuf源码解析
  • 生产环境实战:Spring Cloud Sleuth与Zipkin分布式链路追踪实践
  • 学习React-15-useImperativeHandle
  • 响应式网站案列小学生做电子小报的网站
  • 【AskAI系列课程】:P4.将AI助手集成到Astro网站前端
  • 自注意力机制(Self-Attention)简介
  • App 代上架全流程解析 iOS 应用代上架服务、苹果应用发布步骤、ipa 文件上传与 App Store 审核经验
  • 学习日报 20250921|MQ (Kafka)面试深度复盘
  • 趣味学Solana(启航)
  • 期权末日论效应怎么来的?
  • iOS 混淆与反调试反 Hook 实战,运行时防护、注入检测与安全加固流程
  • 建设工程管理网站邹平建设网站
  • wordpress英文下主题怎么换苏州seo专家教优化网站结构
  • 《灼灼韶华》还原民国上海滩,虎鲸文娱虚拟拍摄让创作突破时空束缚
  • Redo Log 与 Crash Recovery:MySQL 事务持久化的核心技术
  • 金乡网站建设公司云南企业网站
  • 设计模式(C++)详解——职责链模式 (Chain of Responsibility)(1)
  • 酒店网站免费建设国际新闻今天最新
  • 企业产品网络安全日志9月23日-WAF应急
  • 嵌入式硬件工程师:绝缘栅型场效应管
  • HTTPS 请求抓包实战,从请求捕获到解密分析的逐步流程与工具组合(https 请求抓包、iOS 真机、SSL Pinning 排查)
  • 怎么学习cuda?
  • iOS 开发指南全解析 从入门到应用上架、Xcode 使用教程、ipa 打包上传与 App Store 审核实战经验
  • iOS 26 帧率测试实战指南,Liquid Glass 动画性能、滚动滑动帧率对比、旧机型流畅性与 uni-app 优化策略
  • 在网站上签失业保险怎样做网站对公司的重要性
  • php网站模板 php网站源码 PHP源码网