C#与WPF使用mvvm简单案例点击按钮触发弹窗

创建WPF工程文件,以mvvm模式更改页面名称,及创建model类

注意页面的命名以View结尾,模型类以ViewModel结尾

安装 Prism.Core

页面添加一个按钮

XML 复制代码
<Window x:Class="MVVMDemo.Views.MainWindowView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MVVMDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Border>
            <Button Content="测试按钮" 
                        Command="{Binding TestCommand}"  
                        CommandParameter="{Binding RelativeSource={RelativeSource AncestorType=Window}}" 
                        Width="90" Height="50" FontSize="20" />
        </Border>
    </Grid>
</Window>

页面后台代码

cs 复制代码
using MVVMDemo.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MVVMDemo.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindowView : Window
    {
        public MainWindowView()
        {
            InitializeComponent();

            //绑定数据源
            DataContext = new MainWindowViewModel();
        }
    }
}

MainWindowViewModel代码

cs 复制代码
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace MVVMDemo.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        //测试按钮命令
        public ICommand TestCommand
        {
            get => new DelegateCommand(Test);
        }

        private void Test()
        {
            MessageBox.Show("有效触发", "测试mvvm");

        }
    }
}

运行效果

相关推荐
晨星shine1 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530142 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526742 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526742 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf5 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530145 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools7 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的7 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21887 天前
.NET 本地Db数据库-技术方案选型
windows·c#