WPF使用MVVM模式开发

本文用到的有:

  • WPF(.net5)
  • Microsoft.Toolkit.Mvvm
  • 按钮不带参数/带参数点击事件绑定
  • 文本框Text绑定,点击事件绑定

步骤如下:

  1. 创建wpf项目:WpfMVVM

  2. 创建Views、ViewModels两个文件夹
    在这里插入图片描述

  3. nuget添加Microsoft.Toolkit.Mvvm
    在这里插入图片描述

  4. 在ViewModels文件夹添加类MainViewModel

using Microsoft.Toolkit.Mvvm.ComponentModel;
using Microsoft.Toolkit.Mvvm.Input;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfMVVM.ViewModels
{
    public class MainViewModel:ObservableObject
    {
        public RelayCommand ButtonCommand { set; get; }
        public RelayCommand<Window> CloseCommand { set; get; }
        public RelayCommand<TextBox> TextBoxClickCommand { set; get; }

        private string _TextOfBox = "文本框点击命令";
        public string TextOfBox
        {
            set => SetProperty(ref _TextOfBox, value);
            get => _TextOfBox;
        }

        public MainViewModel()
        {
            ButtonCommand = new RelayCommand(OnButtonCommand);
            CloseCommand = new RelayCommand<Window>(OnCloseCommand);
            TextBoxClickCommand = new RelayCommand<TextBox>(OnTextBoxClickCommand);
        }

        private void OnTextBoxClickCommand(TextBox obj)
        {
            obj.Text = "点击了文本框";
        }

        private void OnCloseCommand(Window obj)
        {
            if(MessageBox.Show("要关闭吗?","提示",MessageBoxButton.YesNo)!= MessageBoxResult.Yes)
            {
                return;
            }
            obj.Close();
        }

        private void OnButtonCommand()
        {
            MessageBox.Show("您点击了按钮");
        }
    }
}

  1. 删除MainWindow,并在Views里面创建MainView页面,MainView页面添加两个按钮及一个文本框
    在这里插入图片描述
<Window x:Class="WpfMVVM.Views.MainView"
        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:WpfMVVM.Views" 
        xmlns:viewmodels="clr-namespace:WpfMVVM.ViewModels" d:DataContext="{d:DesignInstance Type=viewmodels:MainViewModel}"
        mc:Ignorable="d" WindowStartupLocation="CenterScreen"
        Title="MainView" Height="450" Width="800" x:Name="window_name">
    <Grid>
        <Button Content="按钮命令" Command="{Binding ButtonCommand}" HorizontalAlignment="Left" Margin="109,51,0,0" VerticalAlignment="Top" Width="86" Height="30"/>
        <Button Content="关闭命令" Command="{Binding CloseCommand}" CommandParameter="{Binding ElementName=window_name}" HorizontalAlignment="Left" Margin="251,51,0,0" VerticalAlignment="Top" Width="97" Height="30"/>
        <TextBox x:Name="textbox_name" HorizontalAlignment="Left" Margin="109,126,0,0" Text="{Binding TextOfBox}" TextWrapping="Wrap" VerticalAlignment="Top" Width="147" Height="25">
            <TextBox.InputBindings>
                <MouseBinding Command="{Binding TextBoxClickCommand}" CommandParameter="{Binding ElementName=textbox_name}" MouseAction="LeftClick"></MouseBinding>
            </TextBox.InputBindings>
        </TextBox>

    </Grid>
</Window>

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.Shapes;
using WpfMVVM.ViewModels;

namespace WpfMVVM.Views
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainView : Window
    {
        protected readonly MainViewModel _VM;
        public MainView()
        {
            InitializeComponent();

            DataContext = _VM = new MainViewModel();
        }
    }
}

  1. 代码地址
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: WPF(Windows Presentation Foundation)是一个基于XAML的应用程序框架,主要面向Windows桌面应用程序的开发MVVM(Model-View-ViewModel)是一种设计模式,它将应用程序分为三个主要的部分:模型,视图和视图模型。在MVVM中,视图和视图模型是分离的,视图模型呈现数据,并且视图与模型直接通信。 在WPF中,MVVM是一个广泛使用模式,并且在实际应用程序中实现起来非常简单。以下是一个MVVM模式实例: 我们建立一个学生管理系统,包括添加学生,编辑学生和显示学生。 首先是数据模型(Model),在这个例子中,我们需要一个Student类,包括姓名,年龄和成绩。 ``` public class Student { public string Name { get; set; } public int Age { get; set; } public float Score { get; set; } } ``` 然后是视图模型(ViewModel),在这里我们需要三个属性:Students(学生列表),SelectedStudent(所选学生),和AddCommand(添加学生命令)。 ``` public class StudentViewModel : INotifyPropertyChanged { private ObservableCollection<Student> _students; private Student _selectedStudent; public ICommand AddCommand { get; private set; } public event PropertyChangedEventHandler PropertyChanged; public ObservableCollection<Student> Students { get { return _students; } set { if (_students != value) { _students = value; OnPropertyChanged("Students"); } } } public Student SelectedStudent { get { return _selectedStudent; } set { if (_selectedStudent != value) { _selectedStudent = value; OnPropertyChanged("SelectedStudent"); } } } public StudentViewModel() { Students = new ObservableCollection<Student>(); AddCommand = new RelayCommand(AddStudent); } private void AddStudent() { Students.Add(new Student() { Name = "New Student" }); } private void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } ``` 最后是视图(View),在这个例子中,我们需要一个包含学生列表和Add按钮的窗口。 ``` <Window x:Class="StudentManager.View.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Student Manager" Height="350" Width="525" DataContext="{StaticResource StudentViewModel}"> <Grid> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <ListView ItemsSource="{Binding Students}" SelectedItem="{Binding SelectedStudent}"> <ListView.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Name}" Margin="5" /> <TextBlock Text="{Binding Age}" Margin="5" /> <TextBlock Text="{Binding Score}" Margin="5" /> </StackPanel> </DataTemplate> </ListView.ItemTemplate> </ListView> <Button Content="Add" Command="{Binding AddCommand}" Grid.Row="1" HorizontalAlignment="Right" Margin="5" Padding="5" /> </Grid> </Window> ``` 在这个例子中,我们使用Data Binding(数据绑定)将视图与视图模型联系起来。数据绑定是指在WPF应用中,允许将数据源与某个控件的属性绑定,当数据源更新时,UI自动更新。为了实现Data Binding,我们使用了INotifyPropertyChanged和RelayCommand。 INotifyPropertyChanged是一个接口,它使ViewModel可以通知视图它的属性已经更新。 RelayCommand是一个实现了ICommand接口的类,它将一些指定的命令关联到一个按钮,当条件满足时该按钮可以被按下。 在这个例子中,我们建立了一个具有添加,编辑和显示学生信息的学生管理器。这个例子演示了MVVM模式如何在WPF实现,希望能帮助你更好的理解如何使用MVVM模式来构建应用程序。 ### 回答2: MVVM(Model-View-ViewModel)是一种软件设计模式,用于将GUI应用程序的UI与其后端逻辑分开。WPF(Windows Presentation Foundation)是一个微软框架,用于创建Windows桌面应用程序。 在WPF使用MVVM模式需要创建三种对象:模型(Model)、视图(View)和视图模型(ViewModel)。模型代表业务逻辑和数据,视图是用户界面,而视图模型则是连接两者的桥梁。 模型中存储着应用程序的数据,我们需要编写类来表示数据结构。视图是XAML文件,包含了UI设计。视图模型是一个C#类,作为一种观察者模式,观察模型的变化并通知视图来更新。 在视图模型中,需要维护着与视图交互的所有数据和命令。我们使用绑定(Binding)来处理两种对象之间的数据交互,从而实现视图和视图模型的解耦。 所以,实现WPF中的MVVM模式需要我们设计好模型、视图和视图模型之间的交互方式,很好的分离了应用程序的UI逻辑和后端业务逻辑,提高了应用程序的可维护性、可扩展性和可重用性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pluto li

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值