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}");
    }
}
相关推荐
SunnyDays101143 分钟前
在 C# 中将邮件转换为 PDF | MSG 转 PDF | EML 转 PDF
c#·邮件转pdf·eml转pdf·msg转pdf
almighty271 小时前
C# WPF实现ComboBox实时搜索与数据绑定
开发语言·c#·wpf·combobox
大飞pkz2 小时前
【设计模式】桥接模式
开发语言·设计模式·c#·桥接模式
玖笙&3 小时前
✨WPF编程基础【1.2】:XAML中的属性
c++·wpf·visual studio
AutomanLV3 小时前
c# datagridview添加list内容
程序人生·c#
Aevget5 小时前
界面控件DevExpress WinForms v25.1 - AI聊天控件功能持续增强
c#·界面控件·winform·devexpress·ui开发
csdn_aspnet5 小时前
在 C# .NETCore 中使用 MongoDB(第 2 部分):使用过滤子句检索文档
mongodb·c#·.netcore
c#上位机6 小时前
wpf之 Popup
wpf
大飞pkz6 小时前
【设计模式】享元模式
开发语言·设计模式·c#·享元模式
Dream achiever6 小时前
4.WPF控件---Border
wpf