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);
         });


     }
 }

三 运行效果

相关推荐
Scout-leaf19 小时前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m62521 小时前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech1 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
laowangpython2 天前
Photoshop 2025 下载安装全攻略
其他·ui·photoshop
2601_962072552 天前
李梦娇常识4600问|题库|打印版
sql·华为od·华为·c#·华为云·.net·harmonyos
风华圆舞2 天前
Flutter + 鸿蒙 Intents Kit:页面直达能力的完整接入方案
flutter·ui·华为·harmonyos
鲲穹AI超级员工2 天前
多款实用配色工具汇总,适配设计、UI 创作等多元场景
ui·色彩设计
m0_547486662 天前
《C#语言程序设计与实践》 全套PPT课件
c语言·c#·c语言程序设计
UXbot2 天前
帮助企业低门槛开展AI应用开发的平台推荐
前端·低代码·ui·交互·产品经理·原型模式·web app
叶帆2 天前
【YFIOs】用C#开发硬件之设备上云
开发语言·unity·c#