#344 – 通过CanExecute控制按钮是可用(The CommandBinding CanExecute Determines Whether a Button is Enabled)

2016-10-12 19:05:13来源:CSDN作者:Libby1984人点击

当你将按钮的Command 属性和一个CommandBinding 实例绑定,同是也设置了ExecutedCanExecute 的处理函数,那么按钮控件将会根据CanExecute 方法的代码自动改变自己的可用性。

假设我们创建了两个按钮,给他们分别绑定 open和close命令。

<StackPanel Orientation="Horizontal" HorizontalAlignment="Center">    <Button Content="Open" Command="ApplicationCommands.Open"            VerticalAlignment="Center" Padding="10,5" Margin="5"/>    <Button Content="Close" Command="ApplicationCommands.Close"            VerticalAlignment="Center" Padding="10,5" Margin="5"/></StackPanel>

并为他们创建CommandBinding 实例和设置处理函数。

public MainWindow(){    this.InitializeComponent();     CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Open_Executed, Open_CanExecute));    CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, Close_Executed, Close_CanExecute));} private bool isOpen = false; public void Open_Executed(object sender, ExecutedRoutedEventArgs e){    MessageBox.Show("Open");    isOpen = true;} public void Open_CanExecute(object sender, CanExecuteRoutedEventArgs e){    e.CanExecute = !isOpen;} public void Close_Executed(object sender, ExecutedRoutedEventArgs e){    MessageBox.Show("Close");    isOpen = false;} public void Close_CanExecute(object sender, CanExecuteRoutedEventArgs e){    e.CanExecute = isOpen;}

上面例子,在CanExecute中将isOpen的值赋给e.CanExecute, 按钮将会根据isOpen的值自动变为可用或者不可用。

原文地址:https://wpf.2000things.com/2011/07/18/344-the-commandbinding-canexecute-event-determines-whether-a-button-is-enabled/

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台