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}");
    }
}
相关推荐
界面开发小八哥1 小时前
界面控件DevExpress XAF v26.1新版亮点——AI Agent Skills
ai·c#·跨平台·devexpress·ui开发·xaf
csdn_aspnet1 小时前
C# 高效便利的处理数据
开发语言·windows·c#
淡海水1 小时前
03-02-线性-List-T-动态数组布局-扩容与操作成本
数据结构·windows·c#·list·编译·clr·机器码
csdn_aspnet12 小时前
C# 在逗号分割的字符串中判断是否包含指定字符
c#·正则·linq·string·regex·contains
宝桥南山12 小时前
Blazor Web Assembly - 体验一下Authentication State从Server共享给Client
microsoft·微软·c#·asp.net·.net·.netcore
淡海水14 小时前
02-06-历史-托管GC机制-垃圾回收如何影响数据结构选择
c#·编译·gc·机器码
Chris _data17 小时前
WPF 上位机开发学习笔记 - 第四天
笔记·学习·wpf
longxiaozhang61 天前
C# static:静态成员,小白也能看懂
开发语言·c#
longxiaozhang61 天前
C#继承:让代码少写一点,偷懒的好方法
开发语言·c#
rockey6271 天前
C#脚本引擎之AScript与DynamicExpresso对比
c#·.net·script·动态脚本