【发布时间】:2016-08-14 14:49:05
【问题描述】:
也许是有史以来最长的问题标题!因为这是一个两部分的问题。
(1) 我不明白设置 NotifyOnValidationError="True" 如何触发对我的 CanExecute 的更新。这里有一点我需要理解的魔法。有人(事物)订阅了我的 ICommand 的 CanExecuteChanged 事件,但调用堆栈指向外部代码,所以我不知道发生了什么。
(2) 也许最重要的后续问题是:为什么它在 MVVM Light RelayCommand 中不起作用! CanExecute 仅在初始化时调用一次,然后再也不调用。与我自己的实现相比,查看 MVVM Light 中 RelayCommand 的源代码并没有发现任何令人窒息的差异。我应该提到 Prism 的 DelegateCommand 似乎也不起作用。
(奖励)也许我以错误的方式处理这个问题?我基本上只是想根据验证失败启用/禁用按钮。
XAML (sn-p):
<TextBox Grid.Column="1" Grid.Row="0">
<Binding Path="X" UpdateSourceTrigger="PropertyChanged" NotifyOnValidationError="True">
<Binding.ValidationRules>
<ExceptionValidationRule></ExceptionValidationRule>
</Binding.ValidationRules>
</Binding>
</TextBox>
<Button Grid.Column="1" Grid.Row="3" Command="{Binding CalculateCommand}">
Calculate
</Button>
中继命令:
public class MyRelayCommand : ICommand
{
readonly Action<object> Execute_;
readonly Predicate<object> CanExecute_;
public MyRelayCommand(Action<object> Execute, Predicate<object> CanExecute)
{
if (Execute == null)
throw new ArgumentNullException("No action to execute for this command.");
Execute_ = Execute;
CanExecute_ = CanExecute;
}
public bool CanExecute(object parameter)
{
return (CanExecute_ == null) ? true : CanExecute_(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
Execute_(parameter);
}
}
视图模型:
private DelegateCommand _calculateCommmand;
public DelegateCommand CalculateCommand
{
get
{
return _calculateCommmand ?? (_calculateCommmand = new DelegateCommand(
() =>
{
Sum = X + X;
},
() =>
{
try
{
Convert.ChangeType(X, TypeCode.Byte);
return true;
}
catch
{
return false;
}
}));
}
}
PS:如果你想在完成后购买我的 X + X 程序,请发送电子邮件至 sales@xplusx.com
【问题讨论】:
标签: wpf mvvm prism mvvm-light