WPF关于Command绑定

发现一位大佬写的Command绑定写法,代码量少,在此记录下,上代码!

首先建立 DelegateCommand.cs

public class DelegateCommand : ICommand
    {
        public Action CommandAction { get; set; }
        public Func<bool> CanExecuteFunc { get; set; }
        public void Execute(object parameter)
        {
            CommandAction();
        }
        public bool CanExecute(object parameter)
        {
            return CanExecuteFunc == null || CanExecuteFunc();
        }
        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }
    }

然后建立ViewModel.cs

public class NotifyIconViewModel
    {
        public ICommand HideWindowCommand
        {
            get
            {
                return new DelegateCommand
                {
                    CommandAction = () => Application.Current.MainWindow.Visibility = Visibility.Hidden,
                };
            }
        }
    }

然后绑定到你需要的xaml.cs中

public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new ViewModel();//把方法绑定上去
        }

最后  就是控件绑定 当然 我这个是内置有的控件方法,只有继承自ButtonBase类的元素才可以直接绑定Command(Button、CheckBox、RadioButton、MenuItem等)

<Button
                    x:Name="btnDataMin"
                    Width="100"
                    Height="30"
                    Margin="20,60,20,20"
                    HorizontalAlignment="Center"
                    VerticalAlignment="Top"
                    Command="{Binding HideWindowCommand}"
                    Content="最小化" />

当前绑定就到此结束,还有其他控件要使用Command绑定的话 就要使用使用System.Windows.Interactivity.dll这个库了,至于如何使用,在百度里面一堆,就是流程有点杂,以后再整理记录。

posted @ 2021-11-17 18:22  FalyEnd  阅读(424)  评论(0)    收藏  举报