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}");
    }
}
相关推荐
EIP低代码平台2 小时前
EIP 低代码平台 - 角色维护
低代码·c#·权限·工作流·netcore
心平气和量大福大7 小时前
C#-WPF-控件-TextBox 数据绑定
开发语言·c#·wpf
-银雾鸢尾-11 小时前
C#中HashTable相关方法
开发语言·c#
geovindu15 小时前
CSharp: Flyweight Pattern
开发语言·后端·c#·.net·享元模式·结构型模式
吴可可12315 小时前
C# CAD二次开发中如何退出窗口
c#
影寂ldy15 小时前
C# WinForm 三种自定义控件 + 完全自定义重绘控件知识点
开发语言·c#
ellis197015 小时前
C#异常相关关键字:Exceptions,throw,try,catch,finally
unity·c#
-银雾鸢尾-16 小时前
C#中的Dictionary相关方法
开发语言·c#
listening77716 小时前
HarmonyOS 6.1 全场景协同实战:从“单机”到“超级终端”的分布式重构
wpf
lzhdim16 小时前
C# 中读取CPU、硬盘和内存温度
开发语言·c#