WPF自定义命令及属性改变处理

1、项目建构
在这里插入图片描述

2、自定义命令

namespace WpfDemo.Base
{
    public class MyCommand : ICommand
    {
        Action executeAction;
        public MyCommand(Action action)
        {
            executeAction = action;
        }
        public event EventHandler? CanExecuteChanged;

        public bool CanExecute(object? parameter)
        {
            return true;
        }

        public void Execute(object? parameter)
        {
            executeAction();
        }
    }
}

3、属性改变

namespace WpfDemo.Base
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler? PropertyChanged;
        public void OnPropertyChanged([CallerMemberName] string propertyName = "")
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

4、界面

<Window x:Class="WpfDemo.MainWindow"
        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:WpfDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <StackPanel>
        <TextBox Height="30" Margin="5" Text="{Binding InputContent}"/>
        <TextBox Height="30" Margin="5" Text="{Binding OutputContent}"/>
        <Button Height="30" Width="75" Content="Button" Command="{Binding ShowCommand}"/>
    </StackPanel>
</Window>

5、后台代码

namespace WpfDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new MainViewModel();
        }
    }
}

6、ViewModel代码

namespace WpfDemo.ViewModels
{
    public class MainViewModel:ViewModelBase
    {
        public MainViewModel()
        {
            ShowCommand = new MyCommand(Show);
        }

        private string? inputContent;

        public string? InputContent
        {
            get { return inputContent; }
            set { inputContent = value; OnPropertyChanged(); }
        }

        private string? outputContent;

        public string? OutputContent
        {
            get { return outputContent; }
            set { outputContent = value; OnPropertyChanged(); }
        }



        public MyCommand ShowCommand { get; set; }
        public void Show()
        {
            OutputContent = InputContent;
            MessageBox.Show("It is blue sky!");
        }
    }
}