WPF的MVVMLight框架

在NuGet中引入该库:

MVVMLight框架中的命令模式的使用:

XML 复制代码
<StackPanel>
    <TextBox Text="{Binding Name}"/>
    <TextBox Text="{Binding Title}"/>
    <Button Content="点我" Command="{Binding ShowCommand}"/>
</StackPanel>
cs 复制代码
DataContext = new MainViewModel();
cs 复制代码
internal class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        Name = "hello";
        ShowCommand = new RelayCommand(Show);
    }
    public RelayCommand ShowCommand { get; set; }
    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            RaisePropertyChanged();
        }
    }
    private string title;
    public string Title
    {
        get { return title; }
        set
        {
            title = value;
            RaisePropertyChanged();
        }
    }

    public void Show()
    {
        Name = "点击了按钮";
        Title = "点击了按钮";
        MessageBox.Show("点击了按钮");
    }
}

如果命令模式是需要从页面传参的情况呢?:

XML 复制代码
<StackPanel>
    <TextBox x:Name="txtIput"/>
    <TextBox Text="{Binding Title}"/>
    <Button Content="点我" Command="{Binding ShowCommand}" CommandParameter="{Binding ElementName=txtIput,Path=Text}"/>
</StackPanel>
cs 复制代码
public MainViewModel()
{
    ShowCommand = new RelayCommand<string>(Show);
}
public RelayCommand<string> ShowCommand { get; set; }
public void Show(string content)
{
    Title = content;
    MessageBox.Show($"需要展示的数据:{content}");
}

使用MVVMLight框架的命令模式,发送消息和接受消息:

MainViewModel.cs类:

cs 复制代码
internal class MainViewModel : ViewModelBase
{
    public MainViewModel()
    {
        ShowCommand = new RelayCommand<string>(Show); // 注册消息
    }
    public RelayCommand<string> ShowCommand { get; set; }

    void Show(string content)
    {
        Messenger.Default.Send(content, "token1"); // 发送器 发送string类型的消息
    }
}

MainWindow.xaml类:

cs 复制代码
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainViewModel();
        // 接收器 接受string类型的消息 第二个参数:收件人
        Messenger.Default.Register<string>(this, "token1", Show);
    }

    void Show(string content)
    {
        MessageBox.Show($"我收到消息了,消息的内容为:{content}");
    }
}
相关推荐
国家一级摸鱼选手9 小时前
[Unity]几何碰撞检测:SAT 分离轴定理详解(从数学原理到 C# 实现)
unity·c#·游戏引擎·分离轴定理(sat)·多边形相交
汤姆宝库1 天前
BPE分词器的完整实现:字节对合并与词表构建
开发语言·人工智能·c#
Risehuxyc1 天前
C# 发展历史
开发语言·c#
kyle~1 天前
C# --- 反射
开发语言·c#
暴走约伯2 天前
【VFX工具链源码拆解 09】终极工业化闭环:基于 ID 规则驱动的全自动场景建档、骨骼挂载与男转女场景迁移
unity·c#·游戏引擎·材质
用户788477316343 天前
WinForms 迁移 WPF:Upgrade Assistant 覆盖 30%,剩下 70% 我手写了六周
c#
寂寞的船3 天前
【Unity知识速递】第13期 Unity 内存泄漏排查实战:从 Memory Profiler 到 Lua 引用泄漏的生产级全链路诊断
unity·junit·c#·游戏引擎·lua
用户3721574261354 天前
C# 提取 PDF 附件:包括文档附件和页面注释附件
c#
寂寞的船4 天前
【Unity Bug挑战】第12期 Awaitable 二次 await 死锁之谜 —— 为什么同一个异步操作等两次就卡死?
unity·c#·游戏引擎·bug
huaqianzkh5 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#