3

Let's say I have a ViewModel

class MyViewModel { public DateTime? InvoiceDate { get; set; } }

and this ViewModel is bound to a text box:

<TextBox Text="{Binding InvoiceDate}" />

Now when the user enters 2015/01/01, InvoiceDate is 2015/01/01. When the user then changes his input to something invalid, e.g. 2015/1234, InvoiceDate is still 2015/01/01. This makes sense, since 2015/1234 cannot be converted to a DateTime?.

However, I want to detect this case and prevent the user from executing a command while invalid data (which cannot be converted to the ViewModel type) is entered. How do I detect this case? I'm sure there's a simple one-liner (like this.AllDataBindingsAreValid()), but I cannot find it.

void MyCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
    e.CanExecute = this.AllDataBindingsAreValid(); // What's it really called?
}
Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • You are looking for `IDataErrorInfo`, you would find it if you search for [c# binding validation](http://stackoverflow.com/q/63646/1997232). – Sinatr Jun 23 '15 at 11:34
  • You might be looking for something like the answer in this post: http://stackoverflow.com/questions/127477/detecting-wpf-validation-errors – Nicholas Jun 23 '15 at 11:41
  • Or maybe [this](http://stackoverflow.com/q/231052/1997232) one? – Sinatr Jun 23 '15 at 11:43
  • @Sinatr that does solve the problem, however it is not the answer to the question – Nicholas Jun 23 '15 at 11:44
  • @Sinatr: I don't need to implement custom validation logic here. I just want to detect when the *default WPF data binding conversion* failed. – Heinzi Jun 23 '15 at 15:42
  • Possible duplicate of [Detecting WPF Validation Errors](https://stackoverflow.com/questions/127477/detecting-wpf-validation-errors) – EpicKip Nov 01 '18 at 07:12

1 Answers1

0

Is this what you're looking for?

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

private 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);
}

Credits to this post .

Community
  • 1
  • 1
Zippy
  • 1,804
  • 5
  • 27
  • 36
  • Thanks, but I *think* this only works when a ValidationRule is set in the binding. But I'll give it a try tomorrow. – Heinzi Jun 23 '15 at 15:44
  • Instead of directly copying the answer you could also close as duplicate. – EpicKip Nov 01 '18 at 07:13