我正在尝试实现这里描述的错误验证解决方案,但我无法找到实现它的方法
private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsValid(sender as DependencyObject);
}
正在从视图接收sender和CanExecuteRoutedEventArgs。这意味着该方法必须在视图中实现。这是怎么回事?CanExecute是Command类的一个属性,它只能在视图模型类中使用。由于从ICommand接口派生只允许以下实现:
public bool CanExecute(object parameter)
{
throw new NotImplementedException();
}
我应该如何在视图模型中接收有关对象的信息,并将它们传递给命令的CanExecute方法?
这是我目前的实现,我已经尝试过解决这个问题,但如果不将方法传递给委托,它是无用的。
视图:
<Button Command="{Binding Path=GenerateBinaryFileCommand}">
<Button.CommandBindings>
<CommandBinding CanExecute="CanExecute"/>
</Button.CommandBindings>
</Button>
视图.cs:
private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
ViewModel vm = (ViewModel )DataContext;
e.CanExecute = vm.IsValid(sender as DependencyObject);
}
ViewModel.cs:
private DelegateCommand generateBinaryCommand;
public bool IsValid(DependencyObject obj)
{
// The dependency object is valid if it has no errors and all
// of its children (that are dependency objects) are error-free.
return !Validation.GetHasError(obj) &&
LogicalTreeHelper.GetChildren(obj)
.OfType<DependencyObject>()
.All(IsValid);
}
public ICommand GenerateBinaryFileCommand
{
get
{
if (generateBinaryCommand == null)
{
// here is where I need to pass the CanExecute method
generateBinaryCommand = new DelegateCommand(generateBinary);
}
return generateBinaryCommand;
}
}
虽然问题本身仍未解决,但我已经通过使用此处描述的UpdateSourceExceptionFilter
解决了这个问题——我建议使用这种方法进行验证。