WPF: 使用CommandManager.InvalidateRequerySuggested手动更新Command状态

30 篇文章 1 订阅

WPF判断命令(Command)是否能够执行是通过ICommand.CanExecute事件,在实际程序中路由命令一般是通过CommandBinding来使命令得到实际操作代码,但是这个CanExecute事件的调用是由WPF控制的,有些时候,比如命令执行后进行一些异步耗时操作,操作完成后会影响CanExecute事件结果,但是WPF不会立即做出反应,那么这个时侯就需要手动调用CommandManager.InvalidateRequerySuggested对命令系统进行一次刷新。
 




//比如下面这个小程序
<Window.CommandBindings>
<CommandBinding Command="New" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" />
</Window.CommandBindings>
<StackPanel>
<Button Command="New">执行工作</Button>
<TextBlock Name="tbl" Text="等待执行"></TextBlock>
</StackPanel>

//
// 事件执行代码
//
privatevoid CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute =!finished;
}

privatevoid CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    System.Threading.ThreadPool.QueueUserWorkItem(dowork);
}

bool finished =false;
void dowork(object obj)
{
    updateUI("开始工作");
    System.Threading.Thread.Sleep(1000);
    updateUI("工作结束");
    finished =true;
}

void updateUI(string msg)
{
    Dispatcher.BeginInvoke((Action)(() => tbl.Text = msg));
}
//程序按钮点击后下面文字显示“工作结束”,这时按钮理应是禁用的(因为此时CanExecute结果是false),但实际上按钮没有被禁用,只有界面发生改变后(如焦点,按键变化,或者按钮再次被点击),按钮才会被禁用,因为此时WPF才调用相应的CanExecute事件。



//手动调用CommandManager.InvalidateRequerySuggested就可以解决问题,注意这个函数只有在UI主线程下调用才会起作用。 

void dowork(object obj)
{
    updateUI("开始工作");
    System.Threading.Thread.Sleep(1000);
    updateUI("工作结束");
    finished =true;
    //手动更新
    updateCommand();
}

void updateCommand()
{
    Dispatcher.BeginInvoke((Action)(() =>CommandManager.InvalidateRequerySuggested()));
}

 

 转至:

https://www.cnblogs.com/zjoch/p/3647236.html

 

示例:

//  System.Windows.Threading.DispatcherTimer.Tick handler
//
//  Updates the current seconds display and calls
//  InvalidateRequerySuggested on the CommandManager to force 
//  the Command to raise the CanExecuteChanged event.
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
    // Updating the Label which displays the current second
    lblSeconds.Content = DateTime.Now.Second;

    // Forcing the CommandManager to raise the RequerySuggested event
    CommandManager.InvalidateRequerySuggested();
}

注解

CommandManager仅在确定命令目标何时更改时注意某些条件,例如键盘焦点更改。 CommandManager如果 无法充分确定导致命令无法执行的条件更改,InvalidateRequerySuggested则可以调用 以强制 CommandManager 引发RequerySuggested事件。

 

转至:

CommandManager.InvalidateRequerySuggested 方法 (System.Windows.Input) | Microsoft Learn

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值