【问题标题】:ICommand pass CanExecute with sender to viewmodelICommand 将 CanExecute 与发送者一起传递给 viewmodel
【发布时间】:2015-04-13 06:49:32
【问题描述】:

我正在尝试实施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();
}

我应该如何在视图模型中接收有关对象的信息并将它们传递给命令的 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;
            }
        }

【问题讨论】:

标签: c# wpf validation mvvm sender


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-29
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    相关资源
    最近更新 更多