ICommand将CanExecute传递给viewmodel

时间:2015-02-12 13:46:56

标签: c# wpf validation mvvm sender

我正在尝试实施here所述的错误验证解决方案,但我无法找到一种方法。在顶部响应中,方法

private void CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = IsValid(sender as DependencyObject);
}

正在从视图中接收发件人和CanExecuteRoutedEventArgs。这意味着必须在视图中实现该方法。这是怎么回事? CanExecute是Command类的属性,只能在viewmodel类中使用。由于从ICommand接口派生只允许以下实现:

public bool CanExecute(object parameter)
{
     throw new NotImplementedException();
}

我应该如何接收有关viewmodel中对象的信息并将它们传递给Command的CanExecute方法?

这是我目前的实现,我已尝试过这方面的工作,但没有将方法传递给委托,它是没用的。

查看:

<Button Command="{Binding Path=GenerateBinaryFileCommand}">
  <Button.CommandBindings>
    <CommandBinding CanExecute="CanExecute"/>
      </Button.CommandBindings>
  </Button>

View.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;
            }
        }

1 个答案:

答案 0 :(得分:0)

虽然问题本身仍未解决,但我已设法使用UpdateSourceExceptionFilter here来解决此问题 - 我建议使用此方法进行验证。