【C#】MVVM知识点汇总-2

在C#中实现MVVM(Model-View-ViewModel)架构时,可以总结以下几个关键知识点,并通过具体的代码示例来进行说明。

 

1. 模型 (Model)

模型包含应用程序中的数据和业务逻辑。通常与数据库交互。

public class User

{

    public int Id { get; set; }

    public string Name { get; set; }

    public int Age { get; set; }

}

 

2. 视图 (View)

视图是UI部分,包括窗口、控件以及布局等。

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="MainWindow" Height="350" Width="525">

   

       

       

   

 

3. 视图模型 (ViewModel)

视图模型封装了应用程序的数据逻辑和业务规则,并且负责与View进行交互,提供给View显示所需的数据以及处理用户输入。

using System.ComponentModel;

 

public class UserViewModel : INotifyPropertyChanged

{

    private User _user = new User();

    

    public UserViewModel()

    {

        _user.Name = "John Doe";

        _user.Age = 30;

    }

 

    public User User

    {

        get => _user;

        set

        {

            if (_user != value)

            {

                _user = value;

                OnPropertyChanged("User");

            }

        }

    }

 

    public event PropertyChangedEventHandler PropertyChanged;

 

    protected void OnPropertyChanged(string name)

    {

        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

    }

}

 

4. 数据绑定 (Data Binding)

数据绑定是MVVM模式的核心。它可以自动同步ViewModel中的属性到视图上对应的控件。

   

 

 

5. 命令 (Command)

命令用于在View和ViewModel之间传递用户操作。

using System.Windows.Input;

 

public class RelayCommand : ICommand

{

    private readonly Action _execute;

    private readonly Func _canExecute;

 

    public RelayCommand(Action execute) : this(execute, null) { }

 

    public RelayCommand(Action execute, Func canExecute)

    {

        _execute = execute ?? throw new ArgumentNullException(nameof(execute));

        _canExecute = canExecute;

    }

 

    public event EventHandler CanExecuteChanged

    {

        add => CommandManager.RequerySuggested += value;

        remove => CommandManager.RequerySuggested -= value;

    }

 

    public bool CanExecute(object parameter)

    {

        return _canExecute == null || _canExecute(parameter);

    }

 

    public void Execute(object parameter)

    {

        _execute?.Invoke(parameter);

    }

}

 

6. 命令绑定 (Command Binding)