首页 > 其他分享 >【WPF】六、WPF命令(ICommand)

【WPF】六、WPF命令(ICommand)

时间:2022-09-03 10:14:26浏览次数:48  
标签:ICommand MyCommand Name executeAction 命令 WPF public

使用Command可以实现UI层跟业务层分离,不必在UI层定义事件方法,近而减少耦合。

下一章是关于内容变更在界面上重新展示。

界面展示_UI层
<Window x:Class="WpfApp1.Window5"
        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:WpfApp1"
        mc:Ignorable="d"
        Title="Window5" Height="450" Width="800">
    <Grid>
        <StackPanel>
            <TextBox Text="{Binding Name}"></TextBox>
            <Button  Command="{Binding ShowCommand }" Content="Button" Height="100"></Button>
        </StackPanel>

    </Grid>
</Window>
界面代码绑定数据
     /// <summary>
    /// Window5.xaml 的交互逻辑
    /// </summary>
    public partial class Window5 : Window
    {
        public Window5()
        {
            this.DataContext = new MainViewModel();

            InitializeComponent();
        }

    }
新建命令类、继承ICommand
 public class MyCommand : ICommand
    {
        public event EventHandler CanExecuteChanged;

        Action executeAction;

        public MyCommand(Action action)
        {
            executeAction = action;
        }


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

        public void Execute(object parameter)
        {
            executeAction();
        }
    }
实现方法_业务层
public class MainViewModel
    {
        public MyCommand ShowCommand { get; set; }
        public String Name { get; set; }


        public MainViewModel()
        {
            Name = "Hello World";
            ShowCommand = new MyCommand(Show);
        }


        public void Show()
        {
            Name = "点击了Button";
            MessageBox.Show(Name);

        }
    }

 

标签:ICommand,MyCommand,Name,executeAction,命令,WPF,public
From: https://www.cnblogs.com/xxxyz/p/16652038.html

相关文章