1

I'm trying to implement the solution for error validation described here, but I can't figure out a way to do it. In the top response, method

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

is receiving sender and CanExecuteRoutedEventArgs from the view. This implies that the method must be implemented in the view. How is this a thing? CanExecute is a property of Command class, which should only be used in the viewmodel class. Since deriving from ICommand interface only allows following implementation:

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

How am I supposed to receieve information about the object in the viewmodel AND pass them to the CanExecute method of the Command?

Here is my current implementation, I've tried working this around, but without passing the method to the delegate it is useless.

View:

<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;
            }
        }
Community
  • 1
  • 1
Ghostli
  • 383
  • 1
  • 3
  • 11
  • see if this links help you. http://stackoverflow.com/questions/28393307/disabling-global-keybindings-in-some-controls-in-wpf-c-sharp/28395791#28395791 – Vinkal Feb 12 '15 at 14:35

1 Answers1

0

While the problem itself remains unresolved, I have managed to work this issue around by using UpdateSourceExceptionFilter described here - I recommend using this approach for validation.

Community
  • 1
  • 1
Ghostli
  • 383
  • 1
  • 3
  • 11