Welcome to the Coach Factor blog. Here you will find all of our ideas on software development. Subscribe at http://blog.nventive.net.
After presenting at Microsoft TechDays the “BlackBelt WPF DataBinding Session”, we received a very interesting question from one of the attendees:
If there are validation rules associated to a binding declared in XAML and validation fails due to invalid data, the value in the target (“onscreen value”) will not be in sync with the value in the source (your business object).
In the end, the folllowing screen shot shows what we want :
By default, the text box would show the invalid value, and would be out of sync with the binded object.
This is what we came up with to change that default behavior: when the validator fails, invoke the binding mechanism as to update the target (onscreen value) with the current value in the source (business object).
Here is the recipe:
1 public interface IRaiseNotifyPropertyChanged
2 {
3 void Raise(string PropertyName);
4 }
1 public void Raise(string PropertyName)
3 if (PropertyChanged != null)
4 {
5 PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
6 }
7 }
1 public string PropertyName { get; set; }
2 public object Target { get; set; }
1 if ((age < Min) || (age > Max))
3 if (Target is IRaiseNotifyPropertyChanged)
5 IRaiseNotifyPropertyChanged t = Target as IRaiseNotifyPropertyChanged;
6 t.Raise(PropertyName);
8
9 return new ValidationResult(false,
10 "Please enter an age in the range: " + Min + " - " + Max + ". You entered : " + value.ToString());
11 }
12 else
13 {
14 return ValidationResult.ValidResult;
15 }
We hope that this will be useful in your WPF adventures !
2008 nVentive. All rights reserved.