在演示中,我有一个按钮来切换 bool 字段isAsking
。我创建了一个只能在isAsking==true
.
一旦我按下 Toggle 按钮,okButton.IsEnable
立即更改,这表明该命令找到了isAsking
.
我感到很困惑,为什么命令对象会注意到一个字段的变化。什么时候CanExecute
会调用?
虽然编写 WPF 应用程序有一段时间了,但我对 WPF 命令还是很陌生。请对此案例进行解释,如果可能,请指出一些相关的文章或博客(我已经阅读了太多关于剪切/粘贴命令的文章)。
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Class="WpfApplication1.MainWindow"
Title="MainWindow" Height="350" Width="525" x:Name="mainWindow" >
<StackPanel>
<Button Name="okButton" Content="Ok" />
<Button Content="Toggle" Click="Button_Click_1"/>
</StackPanel>
</Window>
代码隐藏:
public partial class MainWindow : Window
{
private bool isAsking;
public MainWindow()
{
InitializeComponent();
CommandBinding cb = new CommandBinding();
cb.Command = okCommand;
cb.CanExecute += CanOKExecute;
cb.Executed += cb_Executed;
mainWindow.CommandBindings.Add(cb);
okButton.Command = okCommand;
}
private RoutedCommand okCommand = new RoutedCommand("ok", typeof(MainWindow));
void cb_Executed(object sender, ExecutedRoutedEventArgs e)
{
}
void CanOKExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = isAsking;
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
isAsking = !isAsking;
}
}