MVVM示例程序

目录

[一 定义可通知属性](#一 定义可通知属性)

[二 定义前端并绑定](#二 定义前端并绑定)

[三 运行效果](#三 运行效果)


一 定义可通知属性

cs 复制代码
 internal class MainViewModel : ObservableObject
 {
     /// <summary>
     /// 供前端的Command命令Binding调用
     /// </summary>
     public RelayCommand ShowCommand { get; set; }


     public MainViewModel()
     {
         ShowCommand = new RelayCommand(Show);
     }
     private string name;
     public string Name
     {
         get { return name; }
         set { name = value; OnPropertyChanged(); }
     }
     private string title;
     public string Title
     {
         get { return title; }
         set { title = value; OnPropertyChanged(); }
     }

     public void Show()
     {
         Title = "你点击了按钮 this is Title";
         Name = "你点击了按钮  this is Name";
         MessageBox.Show(Name);
         WeakReferenceMessenger.Default.Send<string, string>(Title, "Token1");
     }
 }

二 定义前端并绑定

cs 复制代码
<Window x:Class="ToolKitMVVMTest.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:ToolKitMVVMTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <TextBox HorizontalAlignment="Left" Margin="145,52,0,0" TextWrapping="Wrap" Text="{Binding Name}" VerticalAlignment="Top" Width="517" Height="189"/>
        <Button Content="Button" HorizontalAlignment="Left" Margin="245,294,0,0" VerticalAlignment="Top" Height="72" Width="278" Command="{Binding ShowCommand}"/>

    </Grid>


</Window>
cs 复制代码
 /// <summary>
 /// Interaction logic for MainWindow.xaml
 /// </summary>
 public partial class MainWindow : Window
 {
     public MainWindow()
     {
         InitializeComponent();
         this.DataContext = new MainViewModel();
         WeakReferenceMessenger.Default.Register<string, string>(this, "Token1", (s, val) =>
         {
             MessageBox.Show(val);
         });


     }
 }

三 运行效果

相关推荐
Vae_Mars2 小时前
C#中的delegate委托
开发语言·c#
公子小六7 小时前
基于.NET的Windows窗体编程之WinForms音频控件
windows·microsoft·c#·.net·音视频·winforms
枫叶丹48 小时前
MCP、A2A、AG-UI:一篇讲清 Agent 协议栈
人工智能·ui·chatgpt·agent·codex
绿浪19848 小时前
c# 结构体 能不能直接封送检测
开发语言·c#
新手unity自用笔记8 小时前
unity基于Socket的网络学习
网络·网络协议·学习·unity·c#·游戏引擎
李高钢8 小时前
【WPF】MVVM 与数据绑定实战:从原理到完整项目
wpf
格林威9 小时前
C#图像像素放大:邻域平均、双线性插值实现像素放大的C#实现代码
开发语言·人工智能·数码相机·计算机视觉·c#·视觉检测·工业相机
用户2986985301414 小时前
C# 实现 PowerPoint 多格式转换:图片、PDF 与 SVG 实战
c#·.net·svg
李高钢15 小时前
【WPF】从 Avalon 到 .NET 10:WPF 平台演进史与特性全览
.net·wpf
山川志~15 小时前
Vue + Element UI 实战:如何实现表格时间、金额字段排序
vue.js·ui·elementui