在我使用过的常规 WPF 项目中
CommandManager.InvalidateRequerySuggested();
为了强制再次执行值转换器。
现在,在 Windows 应用商店应用程序开发中,这个方便的命令不再可用。 是否存在可以解决问题的等效命令或其他命令?
非常感谢您的帮助!
最佳答案
CommandManager
在 WinRT 中不存在。您需要手动刷新监听器。这是我对 DelegateCommand<T>
的示例实现这说明了这一点:
using System;
using System.Windows.Input;
public class DelegateCommand<T> : ICommand
{
private readonly Action<T> m_executeAction;
private readonly Predicate<T> m_canExecutePredicate;
public DelegateCommand(Action<T> executeAction)
: this(executeAction, null)
{
}
public DelegateCommand(Action<T> executeAction, Predicate<T> canExecutePredicate)
{
if (executeAction == null)
{
throw new ArgumentNullException("executeAction");
}
m_executeAction = executeAction;
m_canExecutePredicate = canExecutePredicate;
}
public event EventHandler Executed;
public event EventHandler CanExecuteChanged;
bool ICommand.CanExecute(object parameter)
{
return CanExecute((T)parameter);
}
void ICommand.Execute(object parameter)
{
Execute((T)parameter);
}
public bool CanExecute(T parameter)
{
var result = true;
var canExecutePredicate = m_canExecutePredicate;
if (canExecutePredicate != null)
{
result = canExecutePredicate(parameter);
}
return result;
}
public void Execute(T parameter)
{
m_executeAction(parameter);
RaiseExecuted();
}
public void Refresh()
{
RaiseCanExecuteChanged();
}
protected virtual void RaiseExecuted()
{
var handler = Executed;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
protected virtual void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
此类的 WPF 版本间接使用了 CommandManager.InvalidateRequerySuggested
通过实现 CanExecuteChanged
如下:
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
但是,在 WinRT 中这不受支持,在我的 WinRT 版本中,任何使委托(delegate)命令状态无效的代码都必须调用 Refresh
使 View 中的绑定(bind)项重新查询命令的方法。
我认为针对您的特定问题的最佳解决方案是实现 INotifyPropertyChanged
在你的 View 模型中。调用 PropertyChanged
这个界面上的事件相当于我的Refresh
方法并强制 View 中的绑定(bind)元素重新评估自身,从而重新运行所有关联的 IValueConverter
实例。
关于c# - Windows 应用商店应用程序开发 - InvalidateRequerySuggested,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926016/