isAsking
。我创建了一个命令,只能在isAsking==true
时执行。
一旦我按下切换按钮,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;
}
}
DelegateCommand
,则需要在Command
自身上调用RaiseCanExecuteChanged()
。 - defaultICommand
实现,您可以手动在命令上引发“CanExecuteChanged”事件。 - Steve GreatrexICommand
中的那个事件.. 我还以为Prism已经想到了什么好办法 :) - default