C# WPF入门学习主线篇(三十二)—— 创建Model、View和ViewModel

发布于:2024-06-18 ⋅ 阅读:(22) ⋅ 点赞:(0)

C# WPF入门学习主线篇(三十二)—— 创建Model、View和ViewModel

在这里插入图片描述

在前一篇文章中,我们介绍了MVVM(Model-View-ViewModel)模式的基本概念。本篇将深入探讨如何在实际开发中创建Model、View和ViewModel,并通过一个具体示例来演示它们的交互和实现。

一、创建Model

Model表示应用程序的核心数据和业务逻辑。在MVVM模式中,Model应尽量保持独立,不依赖于UI。以下是一个简单的Model示例:

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Position { get; set; }
}

二、创建View

View表示用户界面,通过XAML定义。View与ViewModel通过数据绑定进行交互,而不直接访问Model。以下是一个简单的View示例:

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp"
        Title="MVVM Demo" Height="200" Width="300">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/>
            <TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/>
            <TextBox Text="{Binding Position, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/>
            <Button Content="Update" Command="{Binding UpdateCommand}" FontSize="16" Margin="10"/>
        </StackPanel>
    </Grid>
</Window>

三、创建ViewModel

ViewModel负责从Model获取数据,并将这些数据提供给View,同时处理用户在View上的交互。ViewModel通常实现INotifyPropertyChanged接口,以便在数据变化时通知View更新UI。

1. 实现INotifyPropertyChanged接口

首先,我们需要一个辅助类来实现命令绑定。以下是一个简单的RelayCommand类:

using System;
using System.Windows.Input;

public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

    public void Execute(object parameter) => _execute(parameter);

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }
}

2. 创建EmployeeViewModel

然后,我们创建一个EmployeeViewModel类来封装Employee数据,并实现数据绑定和命令绑定:

using System.ComponentModel;
using System.Windows.Input;

public class EmployeeViewModel : INotifyPropertyChanged
{
    private Employee _employee;

    public EmployeeViewModel()
    {
        _employee = new Employee { Name = "John Doe", Age = 30, Position = "Software Developer" };
        UpdateCommand = new RelayCommand(UpdateEmployee);
    }

    public string Name
    {
        get => _employee.Name;
        set
        {
            if (_employee.Name != value)
            {
                _employee.Name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }

    public int Age
    {
        get => _employee.Age;
        set
        {
            if (_employee.Age != value)
            {
                _employee.Age = value;
                OnPropertyChanged(nameof(Age));
            }
        }
    }

    public string Position
    {
        get => _employee.Position;
        set
        {
            if (_employee.Position != value)
            {
                _employee.Position = value;
                OnPropertyChanged(nameof(Position));
            }
        }
    }

    public ICommand UpdateCommand { get; }

    private void UpdateEmployee(object parameter)
    {
        Name = "Updated Name";
        Age = 35;
        Position = "Updated Position";
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

3. 绑定ViewModel到View

在View的代码隐藏文件中,我们将ViewModel实例绑定到View的DataContext。

using System.Windows;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new EmployeeViewModel();
        }
    }
}

四、完整代码示例

MainWindow.xaml

<Window x:Class="WpfApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApp"
        Title="MVVM Demo" Height="200" Width="300">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/>
            <TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/>
            <TextBox Text="{Binding Position, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/>
            <Button Content="Update" Command="{Binding UpdateCommand}" FontSize="16" Margin="10"/>
        </StackPanel>
    </Grid>
</Window>

MainWindow.xaml.cs

using System.Windows;

namespace WpfApp
{
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new EmployeeViewModel();
        }
    }
}

Employee.cs

public class Employee
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Position { get; set; }
}

EmployeeViewModel.cs

using System.ComponentModel;
using System.Windows.Input;

public class EmployeeViewModel : INotifyPropertyChanged
{
    private Employee _employee;

    public EmployeeViewModel()
    {
        _employee = new Employee { Name = "John Doe", Age = 30, Position = "Software Developer" };
        UpdateCommand = new RelayCommand(UpdateEmployee);
    }

    public string Name
    {
        get => _employee.Name;
        set
        {
            if (_employee.Name != value)
            {
                _employee.Name = value;
                OnPropertyChanged(nameof(Name));
            }
        }
    }

    public int Age
    {
        get => _employee.Age;
        set
        {
            if (_employee.Age != value)
            {
                _employee.Age = value;
                OnPropertyChanged(nameof(Age));
            }
        }
    }

    public string Position
    {
        get => _employee.Position;
        set
        {
            if (_employee.Position != value)
            {
                _employee.Position = value;
                OnPropertyChanged(nameof(Position));
            }
        }
    }

    public ICommand UpdateCommand { get; }

    private void UpdateEmployee(object parameter)
    {
        Name = "Updated Name";
        Age = 35;
        Position = "Updated Position";
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

RelayCommand.cs

using System;
using System.Windows.Input;

public class RelayCommand : ICommand
{
    private readonly Action<object> _execute;
    private readonly Func<object, bool> _canExecute;

    public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);

    public void Execute(object parameter) => _execute(parameter);

    public event EventHandler CanExecuteChanged
    {
        add => CommandManager.RequerySuggested += value;
        remove => CommandManager.RequerySuggested -= value;
    }
}

五、总结

通过本文,我们详细介绍了如何在WPF中创建Model、View和ViewModel,并通过一个具体示例演示了它们的交互和实现。MVVM模式通过将UI和业务逻辑分离,提高了代码的可维护性和可测试性,是WPF开发中的一种重要架构模式。希望本文能帮助你更好地理解和应用MVVM模式,提高WPF开发的水平。