刷新 WPF 命令 [英] Refresh WPF Command

查看:20
本文介绍了刷新 WPF 命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道我如何强制 CanExecute 在自定义命令上被调用(Josh Smith 的 RelayCommand)?

Does anyone know how I can force CanExecute to get called on a custom command (Josh Smith's RelayCommand)?

通常,只要 UI 上发生交互,就会调用 CanExecute.如果我单击某些东西,我的命令就会更新.

Typically, CanExecute is called whenever interaction occurs on the UI. If I click something, my commands are updated.

我有一种情况,CanExecute 的条件被幕后的计时器打开/关闭.因为这不是由用户交互驱动的,所以在用户与 UI 交互之前不会调用 CanExecute.最终结果是我的 Button 保持启用/禁用状态,直到用户点击它.点击后,就正确更新了.有时 Button 显示为已启用,但当用户单击它时会变为禁用而不是触发.

I have a situation where the condition for CanExecute is getting turned on/off by a timer behind the scenes. Because this is not driven by user interaction, CanExecute is not called until the user interacts with the UI. The end result is that my Button remains enabled/disabled until the user clicks on it. After the click, it is updated correctly. Sometimes the Button appears enabled, but when the user clicks it changes to disabled instead of firing.

当计时器更改影响 CanExecute 的属性时,如何强制更新代码?我尝试在影响 CanExecute 的属性上触发 PropertyChanged (INotifyPropertyChanged),但这没有帮助.

How can I force an update in code when the timer changes the property that affects CanExecute? I tried firing PropertyChanged (INotifyPropertyChanged) on the property that affects CanExecute, but that did not help.

示例 XAML:

<Button Content="Button" Command="{Binding Cmd}"/>

背后的示例代码:

private ICommand m_cmd;
public ICommand Cmd
{
    if (m_cmd == null)
        m_cmd = new RelayCommand(
            (param) => Process(),
            (param) => EnableButton);

    return m_cmd;
}

// Gets updated from a timer (not direct user interaction)
public bool EnableButton { get; set; }

推荐答案

调用 System.Windows.Input.CommandManager.InvalidateRequerySuggested() 强制 CommandManager 引发 RequerySuggested 事件.

Calling System.Windows.Input.CommandManager.InvalidateRequerySuggested() forces the CommandManager to raise the RequerySuggested event.

备注: CommandManager 在确定命令目标何时发生变化时只关注某些条件,例如键盘焦点的变化.在 CommandManager 没有充分确定导致命令无法执行的条件变化的情况下,可以调用 InvalidateRequerySuggested 以强制 CommandManager 引发 RequerySuggested 事件.

Remarks: The CommandManager only pays attention to certain conditions in determining when the command target has changed, such as change in keyboard focus. In situations where the CommandManager does not sufficiently determine a change in conditions that cause a command to not be able to execute, InvalidateRequerySuggested can be called to force the CommandManager to raise the RequerySuggested event.

这篇关于刷新 WPF 命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆