wpf 命令

来源:互联网 发布:百丽运动旗舰店 知乎 编辑:程序博客网 时间:2024/05/19 00:15
<Window x:Class="WpfApplication1.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        Title="Command" Height="175" Width="260" Background="LightBlue">    <StackPanel x:Name="stackPanel">        <Button x:Name="button1" Content="Send Command" Margin="5"/>        <TextBox x:Name="textBoxA" Margin="5,0" Height="100"/>    </StackPanel></Window>

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.Navigation;using System.Windows.Shapes;namespace WpfApplication1{    /// <summary>    /// MainWindow.xaml 的交互逻辑    /// </summary>    public partial class MainWindow : Window    {        public MainWindow()        {            InitializeComponent();            InitializeCommand();        }        private RoutedCommand clearCmd = new RoutedCommand("Clear", typeof(MainWindow));        private void InitializeCommand()        {            this.button1.Command = this.clearCmd;            this.clearCmd.InputGestures.Add(new KeyGesture(Key.C, ModifierKeys.Alt));            this.button1.CommandTarget = this.textBoxA;            CommandBinding cb = new CommandBinding();            cb.Command = this.clearCmd;            cb.CanExecute += new CanExecuteRoutedEventHandler(cb_CanExecute);            cb.Executed += new ExecutedRoutedEventHandler(cb_Executed);            this.stackPanel.CommandBindings.Add(cb);        }        void cb_CanExecute(object sender,CanExecuteRoutedEventArgs e)        {            if(string.IsNullOrEmpty(this.textBoxA.Text))            {                e.CanExecute = false;            }            else            {                e.CanExecute = true;            }            e.Handled = true;        }        void cb_Executed(object sender ,ExecutedRoutedEventArgs e)        {            this.textBoxA.Clear();            e.Handled = true;        }    }}