WPF 通过CommandBinding捕获命令

RoutedCommand与业务逻辑无关,业务逻辑是通过CommandBinding来实现

using System;

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;


namespace Wpf180706
{
    /// <summary>
    /// Interaction logic for Window4.xaml
    /// </summary>
    public partial class Window4 : Window
    {
        public Window4()
        {
            InitializeComponent();
            InitializeCommond();
        }


        private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(Window));




        private void InitializeCommond()
        {
            this.btn.Command = clearCmd;
            clearCmd.InputGestures.Add(new KeyGesture(Key.C,ModifierKeys.Alt));
            //this.btn.CommandTarget = txt;目标可以指定也可以由WPF根据焦点判断
            CommandBinding cb = new CommandBinding();
            cb.Command = clearCmd;
            cb.Executed += cb_Executed;
            cb.CanExecute += cb_CanExecute;
            this.CommandBindings.Add(cb);



        }


        void cb_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txt.Text))
            {
                e.CanExecute = false;
            }
            else
            {
                e.CanExecute = true;
            }


        }


        void cb_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            
            txt.Clear();
            e.Handled = true;
        }
    }
}
posted @ 2018-07-09 09:46  dxm809  阅读(368)  评论(0编辑  收藏  举报