当前位置: 首页 > article >正文

WPF的MVVMLight框架

在NuGet中引入该库:

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

<StackPanel>
    <TextBox Text="{Binding Name}"/>
    <TextBox Text="{Binding Title}"/>
    <Button Content="点我" Command="{Binding ShowCommand}"/>
</StackPanel>
DataContext = new MainViewModel();
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("点击了按钮");
    }
}

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

<StackPanel>
    <TextBox x:Name="txtIput"/>
    <TextBox Text="{Binding Title}"/>
    <Button Content="点我" Command="{Binding ShowCommand}" CommandParameter="{Binding ElementName=txtIput,Path=Text}"/>
</StackPanel>
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类:

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类:

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


http://www.kler.cn/a/546623.html

相关文章:

  • Python的web框架Flask适合哪些具体的应用开发?
  • Spring Boot 中 “约定优于配置” 原则的理解
  • C++ 设计模式-单例模式
  • 如何在 Visual Studio Code 中使用 DeepSeek R1 和 Cline?
  • 用Echarts的柱状图实现圆柱体效果
  • qt UI架构之MVD
  • VUE环境搭建
  • YOLOv11-ultralytics-8.3.67部分代码阅读笔记-plotting.py
  • vue2老版本 npm install 安装失败_安装卡主
  • 给本地模型“投喂“数据
  • 数组_移除元素
  • jenkins-获取当前时间戳
  • Bash 中的运算方式
  • 基于Spring Boot的视频点播系统设计与实现(LW+源码+讲解)
  • 智元机器人开源AgiBot World数据集:具身智能领域的“ImageNet时刻”
  • 计算机毕业设计——Springboot的社区维修平台
  • Unity下ML-Agents第一个示例
  • 【Android开发】安卓手机APP使用机器学习进行QR二维码识别(完整工程资料源码)
  • pgsql用户和权限管理
  • LLM论文笔记 6: Training Compute-Optimal Large Language Models