在演示中,我有一个按钮来切换bool字段isAsking.我创建一个只能在执行时执行的命令isAsking==true.
按下切换按钮后,okButton.IsEnable立即更改,这表示命令找到了更改isAsking.
我觉得很困惑为什么命令对象会注意到字段的变化,什么时候CanExecute会被调用?
虽然编写WPF应用程序已有一段时间了,但我是WPF Command的新手.请对此案例进行解释,如果可能的话,请指出一些相关的文章或博客(我已经阅读了太多关于剪切/粘贴命令的文章).
<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>
Run Code Online (Sandbox Code Playgroud)
代码隐藏:
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) …Run Code Online (Sandbox Code Playgroud)