Related
Warning: Very long and detailed post.
Okay, validation in WPF when using MVVM. I’ve read many things now, looked at many SO questions, and tried many approaches, but everything feels somewhat hacky at some point and I’m really not sure how to do it the right way™.
Ideally, I want to have all validation happen in the view model using IDataErrorInfo; so that’s what I did. There are however different aspects that make this solution be not a complete solution for the whole validation topic.
The situation
Let’s take the following simple form. As you can see, it’s nothing fancy. We just have a two textboxes which bind to a string and int property in the view model each. Furthermore we have a button that is bound to an ICommand.
So for the validation we now have a two choices:
We can run the validation automatically whenever the value of a text box changes. As such the user gets an instant response when he entered something invalid.
We can take this one step further to disable the button when there are any errors.
Or we can run the validation only explicitly when the button is pressed, then showing all errors if applicable. Obviously we can’t disable the button on errors here.
Ideally, I want to implement choice 1. For normal data bindings with activated ValidatesOnDataErrors this is default behavior. So when the text changes, the binding updates the source and triggers the IDataErrorInfo validation for that property; errors are reported back the view. So far so good.
Validation status in the view model
The interesting bit is to let the view model, or the button in this case, know if there are any errors. The way IDataErrorInfo works, it is mainly there to report errors back to the view. So the view can easily see if there are any errors, display them and even show annotations using Validation.Errors. Furthermore, validation always happens looking at a single property.
So having the view model know when there are any errors, or if the validation succeeded, is tricky. A common solution is to simply trigger the IDataErrorInfo validation for all properties in the view model itself. This is often done using a separate IsValid property. The benefit is that this can also be easily used for disabling the command. The drawback is that this might run the validation on all properties a bit too often, but most validations should be simply enough to not hurt the performance. Another solution would be to remember which properties produced errors using the validation and only check those, but that seems a bit overcomplicated and unnecessary for most times.
The bottom line is that this could work fine. IDataErrorInfo provides the validation for all properties, and we can simply use that interface in the view model itself to run the validation there too for the whole object. Introducing the problem:
Binding exceptions
The view model uses actual types for its properties. So in our example, the integer property is an actual int. The text box used in the view however natively only supports text. So when binding to the int in the view model, the data binding engine will automatically perform type conversions—or at least it will try. If you can enter text in a text box meant for numbers, the chances are high that there won’t always be valid numbers inside: So the data binding engine will fail to convert and throw a FormatException.
On the view side, we can easily see that. Exceptions from the binding engine are automatically caught by WPF and are displayed as errors—there isn’t even a need to enable Binding.ValidatesOnExceptions which would be required for exceptions thrown in the setter. The error messages do have a generic text though, so that could be a problem. I have solved this for myself by using a Binding.UpdateSourceExceptionFilter handler, inspecting the exception being thrown and looking at the source property and then generating a less generic error message instead. All that capsulated away into my own Binding markup extension, so I can have all the defaults I need.
So the view is fine. The user makes an error, sees some error feedback and can correct it. The view model however is lost. As the binding engine threw the exception, the source was never updated. So the view model is still on the old value, which isn’t what’s being displayed to the user, and the IDataErrorInfo validation obviously doesn’t apply.
What’s worse, there is no good way for the view model to know this. At least, I haven’t found a good solution for this yet. What would be possible is to have the view report back to the view model that there was an error. This could be done by data binding the Validation.HasError property back to the view model (which isn’t possible directly), so the view model could check the view’s state first.
Another option would be to relay the exception handled in Binding.UpdateSourceExceptionFilter to the view model, so it would be notified of it as well. The view model could even provide some interface for the binding to report these things, allowing for custom error messages instead of generic per-type ones. But that would create a stronger coupling from the view to the view model, which I generally want to avoid.
Another “solution” would be to get rid of all typed properties, use plain string properties and do the conversion in the view model instead. This obviously would move all validation to the view model, but also mean an incredible amount of duplication of things the data binding engine usually takes care of. Furthermore it would change the semantics of the view model. For me, a view is built for the view model and not the reverse—of course the design of the view model depends on what we imagine the view to do, but there’s still general freedom how the view does that. So the view model defines an int property because there is a number; the view can now use a text box (allowing all these problems), or use something that natively works with numbers. So no, changing the types of the properties to string is not an option for me.
In the end, this is a problem of the view. The view (and its data binding engine) is responsible for giving the view model proper values to work with. But in this case, there seems to be no good way to tell the view model that it should invalidate the old property value.
BindingGroups
Binding groups are one way I tried to tackle this. Binding groups have the ability to group all validations, including IDataErrorInfo and thrown exceptions. If available to the view model, they even have a mean to check the validation status for all of those validation sources, for example using CommitEdit.
By default, binding groups implement choice 2 from above. They make the bindings update explicitly, essentially adding an additional uncommitted state. So when clicking the button, the command can commit those changes, trigger the source updates and all validations and get a single result if it succeeded. So the command’s action could be this:
if (bindingGroup.CommitEdit())
SaveEverything();
CommitEdit will only return true if all validations succeeded. It will take IDataErrorInfo into account and also check binding exceptions. This seems to be a perfect solution for choice 2. The only thing that is a bit of a hassle is managing the binding group with the bindings, but I’ve built myself something that mostly takes care of this (related).
If a binding group is present for a binding, the binding will default to an explicit UpdateSourceTrigger. To implement choice 1 from above using binding groups, we basically have to change the trigger. As I have a custom binding extension anyway, this is rather simple, I just set it to LostFocus for all.
So now, the bindings will still update whenever a text field changes. If the source could be updated (binding engine throws no exception) then IDataErrorInfo will run as usual. If it couldn’t be updated the view is still able to see it. And if we click our button, the underlying command can call CommitEdit (although nothing needs to be committed) and get the total validation result to see if it can continue.
We might not be able to disable the button easily this way. At least not from the view model. Checking the validation over and over is not really a good idea just to update the command status, and the view model isn’t notified when a binding engine exception is thrown anyway (which should disable the button then)—or when it goes away to enable the button again. We could still add a trigger to disable the button in the view using the Validation.HasError so it’s not impossible.
Solution?
So overall, this seems to be the perfect solution. What is my problem with it though? To be honest, I’m not entirely sure. Binding groups are a complex thing that seem to be usually used in smaller groups, possibly having multiple binding groups in a single view. By using one big binding group for the whole view just to ensure my validation, it feels as if I’m abusing it. And I just keep thinking, that there must be a better way to solve this whole situation, because surely I can’t be the only one having these problems. And so far I haven’t really seen many people use binding groups for validation with MVVM at all, so it just feels odd.
So, what exactly is the proper way to do validation in WPF with MVVM while being able to check for binding engine exceptions?
My solution (/hack)
First of all, thanks for your input! As I have written above, I’m using IDataErrorInfo already to do my data validation and I personally believe it’s the most comfortable utility to do the validation job. I’m using utilities similar to what Sheridan suggested in his answer below, so maintaining works fine too.
In the end, my problem boiled down to the binding exception issue, where the view model just wouldn’t know about when it happened. While I could handle this with binding groups as detailed above, I still decided against it, as I just didn’t feel all that comfortable with it. So what did I do instead?
As I mentioned above, I detect binding exceptions on the view-side by listening to a binding’s UpdateSourceExceptionFilter. In there, I can get a reference to the view model from the binding expression’s DataItem. I then have an interface IReceivesBindingErrorInformation which registers the view model as a possible receiver for information about binding errors. I then use that to pass the binding path and the exception to the view model:
object OnUpdateSourceExceptionFilter(object bindExpression, Exception exception)
{
BindingExpression expr = (bindExpression as BindingExpression);
if (expr.DataItem is IReceivesBindingErrorInformation)
{
((IReceivesBindingErrorInformation)expr.DataItem).ReceiveBindingErrorInformation(expr.ParentBinding.Path.Path, exception);
}
// check for FormatException and produce a nicer error
// ...
}
In the view model I then remember whenever I am notified about a path’s binding expression:
HashSet<string> bindingErrors = new HashSet<string>();
void IReceivesBindingErrorInformation.ReceiveBindingErrorInformation(string path, Exception exception)
{
bindingErrors.Add(path);
}
And whenever the IDataErrorInfo revalidates a property, I know that the binding worked, and I can clear the property from the hash set.
In the view model I then can check if the hash set contains any items and abort any action that requires the data to be validated completely. It might not be the nicest solution due to the coupling from the view to the view model, but using that interface it’s at least somewhat less a problem.
Warning: Long answer also
I use the IDataErrorInfo interface for validation, but I have customised it to my needs. I think that you'll find that it solves some of your problems too. One difference to your question is that I implement it in my base data type class.
As you pointed out, this interface just deals with one property at a time, but clearly in this day and age, that's no good. So I just added a collection property to use instead:
protected ObservableCollection<string> errors = new ObservableCollection<string>();
public virtual ObservableCollection<string> Errors
{
get { return errors; }
}
To address your problem of not being able to display external errors (in your case from the view, but in mine from the view model), I simply added another collection property:
protected ObservableCollection<string> externalErrors = new ObservableCollection<string>();
public ObservableCollection<string> ExternalErrors
{
get { return externalErrors; }
}
I have an HasError property which looks at my collection:
public virtual bool HasError
{
get { return Errors != null && Errors.Count > 0; }
}
This enables me to bind this to Grid.Visibility using a custom BoolToVisibilityConverter, eg. to show a Grid with a collection control inside that shows the errors when there are any. It also lets me change a Brush to Red to highlight an error (using another Converter), but I guess you get the idea.
Then in each data type, or model class, I override the Errors property and implement the Item indexer (simplified in this example):
public override ObservableCollection<string> Errors
{
get
{
errors = new ObservableCollection<string>();
errors.AddUniqueIfNotEmpty(this["Name"]);
errors.AddUniqueIfNotEmpty(this["EmailAddresses"]);
errors.AddUniqueIfNotEmpty(this["SomeOtherProperty"]);
errors.AddRange(ExternalErrors);
return errors;
}
}
public override string this[string propertyName]
{
get
{
string error = string.Empty;
if (propertyName == "Name" && Name.IsNullOrEmpty()) error = "You must enter the Name field.";
else if (propertyName == "EmailAddresses" && EmailAddresses.Count == 0) error = "You must enter at least one e-mail address into the Email address(es) field.";
else if (propertyName == "SomeOtherProperty" && SomeOtherProperty.IsNullOrEmpty()) error = "You must enter the SomeOtherProperty field.";
return error;
}
}
The AddUniqueIfNotEmpty method is a custom extension method and 'does what is says on the tin'. Note how it will call each property that I want to validate in turn and compile a collection from them, ignoring duplicate errors.
Using the ExternalErrors collection, I can validate things that I can't validate in the data class:
private void ValidateUniqueName(Genre genre)
{
string errorMessage = "The genre name must be unique";
if (!IsGenreNameUnique(genre))
{
if (!genre.ExternalErrors.Contains(errorMessage)) genre.ExternalErrors.Add(errorMessage);
}
else genre.ExternalErrors.Remove(errorMessage);
}
To address your point regarding the situation where a user enters an alphabetical character into a int field, I tend to use a custom IsNumeric AttachedProperty for the TextBox, eg. I don't let them make these kinds of errors. I always feel that it's better to stop it, than to let it happen and then fix it.
Overall I'm really happy with my validation ability in WPF and am not left wanting at all.
To end with and for completeness, I felt that I should alert you to the fact that there is now an INotifyDataErrorInfo interface which includes some of this added functionality. You can find out more from the INotifyDataErrorInfo Interface page on MSDN.
UPDATE >>>
Yes, the ExternalErrors property just let's me add errors that relate to a data object from outside that object... sorry, my example wasn't complete... if I'd have shown you the IsGenreNameUnique method, you would have seen that it uses LinQ on all of the Genre data items in the collection to determine whether the object's name is unique or not:
private bool IsGenreNameUnique(Genre genre)
{
return Genres.Where(d => d.Name != string.Empty && d.Name == genre.Name).Count() == 1;
}
As for your int/string problem, the only way I can see you getting those errors in your data class is if you declare all your properties as object, but then you'd have an awful lot of casting to do. Perhaps you could double your properties like this:
public object FooObject { get; set; } // Implement INotifyPropertyChanged
public int Foo
{
get { return FooObject.GetType() == typeof(int) ? int.Parse(FooObject) : -1; }
}
Then if Foo was used in code and FooObject was used in the Binding, you could do this:
public override string this[string propertyName]
{
get
{
string error = string.Empty;
if (propertyName == "FooObject" && FooObject.GetType() != typeof(int))
error = "Please enter a whole number for the Foo field.";
...
return error;
}
}
That way you could fulfil your requirements, but you'll have a lot of extra code to add.
In my opinion, the problem lies in validation happening at too many places. I also wished to write all my validation login in ViewModel but all those number binding were making my ViewModel crazy.
I solved this problem by creating a binding that never fails. Obviously, if a binding is always successful then the type itself has to handle the error conditions gracefully.
Failable Value Type
I started by creating a generic type which would gracefully support the failed conversions:
public struct Failable<T>
{
public T Value { get; private set; }
public string Text { get; private set; }
public bool IsValid { get; private set; }
public Failable(T value)
{
Value = value;
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
Text = converter.ConvertToString(value);
IsValid = true;
}
catch
{
Text = String.Empty;
IsValid = false;
}
}
public Failable(string text)
{
Text = text;
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
Value = (T)converter.ConvertFromString(text);
IsValid = true;
}
catch
{
Value = default(T);
IsValid = false;
}
}
}
Note that even if the type fails to initialise because of invalid input string (second constructor), it quietly stores the invalid state along with invalid text also. This is required in order to support the round-trip of binding even in case of wrong input.
Generic Value Converter
A generic value converter could be written using above type:
public class StringToFailableConverter<T> : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(Failable<T>))
throw new InvalidOperationException("Invalid value type.");
if (targetType != typeof(string))
throw new InvalidOperationException("Invalid target type.");
var rawValue = (Failable<T>)value;
return rawValue.Text;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(string))
throw new InvalidOperationException("Invalid value type.");
if (targetType != typeof(Failable<T>))
throw new InvalidOperationException("Invalid target type.");
return new Failable<T>(value as string);
}
}
XAML Handy Converters
Since creating and using the instances of generics is pain in XAML, lets make static instances of common converters:
public static class Failable
{
public static StringToFailableConverter<Int32> Int32Converter { get; private set; }
public static StringToFailableConverter<double> DoubleConverter { get; private set; }
static Failable()
{
Int32Converter = new StringToFailableConverter<Int32>();
DoubleConverter = new StringToFailableConverter<Double>();
}
}
Other value types can be extended easily.
Usage
Usage is pretty simple, just need to change the type from int to Failable<int>:
ViewModel
public Failable<int> NumberValue
{
//Custom logic along with validation
//using IsValid property
}
XAML
<TextBox Text="{Binding NumberValue,Converter={x:Static local:Failable.Int32Converter}}"/>
This way, you can use the same validation mechanism (IDataErrorInfo or INotifyDataErrorInfo or anything else) in ViewModel by checking the IsValid property. If IsValid is true, you can directly use the Value.
Ok, I believe I have found the answer you were looking for...
It will not be easy to explain - but..
Very easy to understand once explained...
I do think It is most accurate/"certified" to MVVM viewed as "standard" or at the least attempted standard.
But before we begin.. you need to change a concept which you got used to regarding MVVM:
"Furthermore it would change the semantics of the view model. For me,
a view is built for the view model and not the reverse—of course the design
of the view model depends on what we imagine the view to do,
but there’s still general freedom how the view does that"
That paragraph is the source of your problem.. - why?
Because you are stating the View-Model has no role to adjust itself to the View..
That is wrong in many ways - as I'll prove to you very simply..
If you have a property such as:
public Visibility MyPresenter { get...
What is Visibility if not something that serves the View?
The type itself and the name that will be given to the property is definitely made up for the view.
There two distinguishable View-Models categories in MVVM according to my experience:
Presenter View Model - which is to be hooked to buttons, menus, Tab Items etc....
Entity View Model - which is to be hocked to controls that brings the entity data to screen.
These are two different - completely different concerns.
And now to the solution:
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class VmSomeEntity : ViewModelBase, INotifyDataErrorInfo
{
//This one is part of INotifyDataErrorInfo interface which I will not use,
//perhaps in more complicated scenarios it could be used to let some other VM know validation changed.
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
//will hold the errors found in validation.
public Dictionary<string, string> ValidationErrors = new Dictionary<string, string>();
//the actual value - notice it is 'int' and not 'string'..
private int storageCapacityInBytes;
//this is just to keep things sane - otherwise the view will not be able to send whatever the user throw at it.
//we want to consume what the user throw at us and validate it - right? :)
private string storageCapacityInBytesWrapper;
//This is a property to be served by the View.. important to understand the tactic used inside!
public string StorageCapacityInBytes
{
get { return storageCapacityInBytesWrapper ?? storageCapacityInBytes.ToString(); }
set
{
int result;
var isValid = int.TryParse(value, out result);
if (isValid)
{
storageCapacityInBytes = result;
storageCapacityInBytesWrapper = null;
RaisePropertyChanged();
}
else
storageCapacityInBytesWrapper = value;
HandleValidationError(isValid, "StorageCapacityInBytes", "Not a number.");
}
}
//Manager for the dictionary
private void HandleValidationError(bool isValid, string propertyName, string validationErrorDescription)
{
if (!string.IsNullOrEmpty(propertyName))
{
if (isValid)
{
if (ValidationErrors.ContainsKey(propertyName))
ValidationErrors.Remove(propertyName);
}
else
{
if (!ValidationErrors.ContainsKey(propertyName))
ValidationErrors.Add(propertyName, validationErrorDescription);
else
ValidationErrors[propertyName] = validationErrorDescription;
}
}
}
// this is another part of the interface - will be called automatically
public IEnumerable GetErrors(string propertyName)
{
return ValidationErrors.ContainsKey(propertyName)
? ValidationErrors[propertyName]
: null;
}
// same here, another part of the interface - will be called automatically
public bool HasErrors
{
get
{
return ValidationErrors.Count > 0;
}
}
}
And now somewhere in your code - your button command 'CanExecute' method can add to its implementation a call to VmEntity.HasErrors.
And may peace be upon your code regarding validation from now on :)
The drawback is that this might run the validation on all properties a
bit too often, but most validations should be simply enough to not
hurt the performance. Another solution would be to remember which
properties produced errors using the validation and only check those,
but that seems a bit overcomplicated and unecessary for most times.
You don't need to track which properties have errors; you only need to know that errors exist. The view model can maintain a list of errors (also useful for displaying an error summary), and the IsValid property can simply be a reflection of whether the list has anything. You don't need to check everything each time IsValid is called, as long as you ensure that the error summary is current and that IsValid is refreshed each time it changes.
In the end, this is a problem of the view. The view (and its data
binding engine) is responsible for giving the view model proper values
to work with. But in this case, there seems to be no good way to tell
the view model that it should invalidate the old property value.
You can listen to errors within the container that is bound to the view model:
container.AddHandler(Validation.ErrorEvent, Container_Error);
...
void Container_Error(object sender, ValidationErrorEventArgs e) {
...
}
This notifies you when errors are added or removed, and you can identify binding exceptions by whether e.Error.Exception exists, so your view can maintain a list of binding exceptions and inform the view model of it.
But any solution to this problem will always be a hack, because the view is not filling its role properly, which is giving the user a means of reading and updating the view model structure. This should be seen as a temporary solution until you correctly present the user with some kind of "integer box" instead of a text box.
Here's an effort to simplify things if you don't want to implement tons of additional code...
The scenario is that you have an int property in your viewmodel (could be decimal or another non-string type) and you bind a textbox to it in your view.
You have validation in your viewmodel that fires in the setter of the property.
In the view a user enters 123abc and the view logic highlights the error in the view, but can't set the property because the value is the wrong type. The setter never gets called.
The simplest solution is to change your int property in the viewmodel to be a string property, and cast the values into and out of it from the model. This allows the bad text to hit the setter of your property, and your validation code can then check the data and reject it as appropriate.
IMHO validation in WPF is broken, as can be seen from the elaborate (and ingenious) ways people have tried to work around the problem given previously. For me I don't want to add a huge amount of extra code or implement my own type classes to enable a textbox to validate so basing these properties on strings is something I can live with, even if it does feel like a bit of a kludge.
Microsoft should look at fixing this so that the scenario of invalid user input in a textbox bound to an int or decimal property can somehow communicate this fact elegantly to the viewmodel. It should be possible, for instance for them to create a new bound property for a XAML control to communicate view logic validation errors to a property in the viewmodel.
Thanks and respect to the other guys that have provided detailed answers to this topic.
Warning: Very long and detailed post.
Okay, validation in WPF when using MVVM. I’ve read many things now, looked at many SO questions, and tried many approaches, but everything feels somewhat hacky at some point and I’m really not sure how to do it the right way™.
Ideally, I want to have all validation happen in the view model using IDataErrorInfo; so that’s what I did. There are however different aspects that make this solution be not a complete solution for the whole validation topic.
The situation
Let’s take the following simple form. As you can see, it’s nothing fancy. We just have a two textboxes which bind to a string and int property in the view model each. Furthermore we have a button that is bound to an ICommand.
So for the validation we now have a two choices:
We can run the validation automatically whenever the value of a text box changes. As such the user gets an instant response when he entered something invalid.
We can take this one step further to disable the button when there are any errors.
Or we can run the validation only explicitly when the button is pressed, then showing all errors if applicable. Obviously we can’t disable the button on errors here.
Ideally, I want to implement choice 1. For normal data bindings with activated ValidatesOnDataErrors this is default behavior. So when the text changes, the binding updates the source and triggers the IDataErrorInfo validation for that property; errors are reported back the view. So far so good.
Validation status in the view model
The interesting bit is to let the view model, or the button in this case, know if there are any errors. The way IDataErrorInfo works, it is mainly there to report errors back to the view. So the view can easily see if there are any errors, display them and even show annotations using Validation.Errors. Furthermore, validation always happens looking at a single property.
So having the view model know when there are any errors, or if the validation succeeded, is tricky. A common solution is to simply trigger the IDataErrorInfo validation for all properties in the view model itself. This is often done using a separate IsValid property. The benefit is that this can also be easily used for disabling the command. The drawback is that this might run the validation on all properties a bit too often, but most validations should be simply enough to not hurt the performance. Another solution would be to remember which properties produced errors using the validation and only check those, but that seems a bit overcomplicated and unnecessary for most times.
The bottom line is that this could work fine. IDataErrorInfo provides the validation for all properties, and we can simply use that interface in the view model itself to run the validation there too for the whole object. Introducing the problem:
Binding exceptions
The view model uses actual types for its properties. So in our example, the integer property is an actual int. The text box used in the view however natively only supports text. So when binding to the int in the view model, the data binding engine will automatically perform type conversions—or at least it will try. If you can enter text in a text box meant for numbers, the chances are high that there won’t always be valid numbers inside: So the data binding engine will fail to convert and throw a FormatException.
On the view side, we can easily see that. Exceptions from the binding engine are automatically caught by WPF and are displayed as errors—there isn’t even a need to enable Binding.ValidatesOnExceptions which would be required for exceptions thrown in the setter. The error messages do have a generic text though, so that could be a problem. I have solved this for myself by using a Binding.UpdateSourceExceptionFilter handler, inspecting the exception being thrown and looking at the source property and then generating a less generic error message instead. All that capsulated away into my own Binding markup extension, so I can have all the defaults I need.
So the view is fine. The user makes an error, sees some error feedback and can correct it. The view model however is lost. As the binding engine threw the exception, the source was never updated. So the view model is still on the old value, which isn’t what’s being displayed to the user, and the IDataErrorInfo validation obviously doesn’t apply.
What’s worse, there is no good way for the view model to know this. At least, I haven’t found a good solution for this yet. What would be possible is to have the view report back to the view model that there was an error. This could be done by data binding the Validation.HasError property back to the view model (which isn’t possible directly), so the view model could check the view’s state first.
Another option would be to relay the exception handled in Binding.UpdateSourceExceptionFilter to the view model, so it would be notified of it as well. The view model could even provide some interface for the binding to report these things, allowing for custom error messages instead of generic per-type ones. But that would create a stronger coupling from the view to the view model, which I generally want to avoid.
Another “solution” would be to get rid of all typed properties, use plain string properties and do the conversion in the view model instead. This obviously would move all validation to the view model, but also mean an incredible amount of duplication of things the data binding engine usually takes care of. Furthermore it would change the semantics of the view model. For me, a view is built for the view model and not the reverse—of course the design of the view model depends on what we imagine the view to do, but there’s still general freedom how the view does that. So the view model defines an int property because there is a number; the view can now use a text box (allowing all these problems), or use something that natively works with numbers. So no, changing the types of the properties to string is not an option for me.
In the end, this is a problem of the view. The view (and its data binding engine) is responsible for giving the view model proper values to work with. But in this case, there seems to be no good way to tell the view model that it should invalidate the old property value.
BindingGroups
Binding groups are one way I tried to tackle this. Binding groups have the ability to group all validations, including IDataErrorInfo and thrown exceptions. If available to the view model, they even have a mean to check the validation status for all of those validation sources, for example using CommitEdit.
By default, binding groups implement choice 2 from above. They make the bindings update explicitly, essentially adding an additional uncommitted state. So when clicking the button, the command can commit those changes, trigger the source updates and all validations and get a single result if it succeeded. So the command’s action could be this:
if (bindingGroup.CommitEdit())
SaveEverything();
CommitEdit will only return true if all validations succeeded. It will take IDataErrorInfo into account and also check binding exceptions. This seems to be a perfect solution for choice 2. The only thing that is a bit of a hassle is managing the binding group with the bindings, but I’ve built myself something that mostly takes care of this (related).
If a binding group is present for a binding, the binding will default to an explicit UpdateSourceTrigger. To implement choice 1 from above using binding groups, we basically have to change the trigger. As I have a custom binding extension anyway, this is rather simple, I just set it to LostFocus for all.
So now, the bindings will still update whenever a text field changes. If the source could be updated (binding engine throws no exception) then IDataErrorInfo will run as usual. If it couldn’t be updated the view is still able to see it. And if we click our button, the underlying command can call CommitEdit (although nothing needs to be committed) and get the total validation result to see if it can continue.
We might not be able to disable the button easily this way. At least not from the view model. Checking the validation over and over is not really a good idea just to update the command status, and the view model isn’t notified when a binding engine exception is thrown anyway (which should disable the button then)—or when it goes away to enable the button again. We could still add a trigger to disable the button in the view using the Validation.HasError so it’s not impossible.
Solution?
So overall, this seems to be the perfect solution. What is my problem with it though? To be honest, I’m not entirely sure. Binding groups are a complex thing that seem to be usually used in smaller groups, possibly having multiple binding groups in a single view. By using one big binding group for the whole view just to ensure my validation, it feels as if I’m abusing it. And I just keep thinking, that there must be a better way to solve this whole situation, because surely I can’t be the only one having these problems. And so far I haven’t really seen many people use binding groups for validation with MVVM at all, so it just feels odd.
So, what exactly is the proper way to do validation in WPF with MVVM while being able to check for binding engine exceptions?
My solution (/hack)
First of all, thanks for your input! As I have written above, I’m using IDataErrorInfo already to do my data validation and I personally believe it’s the most comfortable utility to do the validation job. I’m using utilities similar to what Sheridan suggested in his answer below, so maintaining works fine too.
In the end, my problem boiled down to the binding exception issue, where the view model just wouldn’t know about when it happened. While I could handle this with binding groups as detailed above, I still decided against it, as I just didn’t feel all that comfortable with it. So what did I do instead?
As I mentioned above, I detect binding exceptions on the view-side by listening to a binding’s UpdateSourceExceptionFilter. In there, I can get a reference to the view model from the binding expression’s DataItem. I then have an interface IReceivesBindingErrorInformation which registers the view model as a possible receiver for information about binding errors. I then use that to pass the binding path and the exception to the view model:
object OnUpdateSourceExceptionFilter(object bindExpression, Exception exception)
{
BindingExpression expr = (bindExpression as BindingExpression);
if (expr.DataItem is IReceivesBindingErrorInformation)
{
((IReceivesBindingErrorInformation)expr.DataItem).ReceiveBindingErrorInformation(expr.ParentBinding.Path.Path, exception);
}
// check for FormatException and produce a nicer error
// ...
}
In the view model I then remember whenever I am notified about a path’s binding expression:
HashSet<string> bindingErrors = new HashSet<string>();
void IReceivesBindingErrorInformation.ReceiveBindingErrorInformation(string path, Exception exception)
{
bindingErrors.Add(path);
}
And whenever the IDataErrorInfo revalidates a property, I know that the binding worked, and I can clear the property from the hash set.
In the view model I then can check if the hash set contains any items and abort any action that requires the data to be validated completely. It might not be the nicest solution due to the coupling from the view to the view model, but using that interface it’s at least somewhat less a problem.
Warning: Long answer also
I use the IDataErrorInfo interface for validation, but I have customised it to my needs. I think that you'll find that it solves some of your problems too. One difference to your question is that I implement it in my base data type class.
As you pointed out, this interface just deals with one property at a time, but clearly in this day and age, that's no good. So I just added a collection property to use instead:
protected ObservableCollection<string> errors = new ObservableCollection<string>();
public virtual ObservableCollection<string> Errors
{
get { return errors; }
}
To address your problem of not being able to display external errors (in your case from the view, but in mine from the view model), I simply added another collection property:
protected ObservableCollection<string> externalErrors = new ObservableCollection<string>();
public ObservableCollection<string> ExternalErrors
{
get { return externalErrors; }
}
I have an HasError property which looks at my collection:
public virtual bool HasError
{
get { return Errors != null && Errors.Count > 0; }
}
This enables me to bind this to Grid.Visibility using a custom BoolToVisibilityConverter, eg. to show a Grid with a collection control inside that shows the errors when there are any. It also lets me change a Brush to Red to highlight an error (using another Converter), but I guess you get the idea.
Then in each data type, or model class, I override the Errors property and implement the Item indexer (simplified in this example):
public override ObservableCollection<string> Errors
{
get
{
errors = new ObservableCollection<string>();
errors.AddUniqueIfNotEmpty(this["Name"]);
errors.AddUniqueIfNotEmpty(this["EmailAddresses"]);
errors.AddUniqueIfNotEmpty(this["SomeOtherProperty"]);
errors.AddRange(ExternalErrors);
return errors;
}
}
public override string this[string propertyName]
{
get
{
string error = string.Empty;
if (propertyName == "Name" && Name.IsNullOrEmpty()) error = "You must enter the Name field.";
else if (propertyName == "EmailAddresses" && EmailAddresses.Count == 0) error = "You must enter at least one e-mail address into the Email address(es) field.";
else if (propertyName == "SomeOtherProperty" && SomeOtherProperty.IsNullOrEmpty()) error = "You must enter the SomeOtherProperty field.";
return error;
}
}
The AddUniqueIfNotEmpty method is a custom extension method and 'does what is says on the tin'. Note how it will call each property that I want to validate in turn and compile a collection from them, ignoring duplicate errors.
Using the ExternalErrors collection, I can validate things that I can't validate in the data class:
private void ValidateUniqueName(Genre genre)
{
string errorMessage = "The genre name must be unique";
if (!IsGenreNameUnique(genre))
{
if (!genre.ExternalErrors.Contains(errorMessage)) genre.ExternalErrors.Add(errorMessage);
}
else genre.ExternalErrors.Remove(errorMessage);
}
To address your point regarding the situation where a user enters an alphabetical character into a int field, I tend to use a custom IsNumeric AttachedProperty for the TextBox, eg. I don't let them make these kinds of errors. I always feel that it's better to stop it, than to let it happen and then fix it.
Overall I'm really happy with my validation ability in WPF and am not left wanting at all.
To end with and for completeness, I felt that I should alert you to the fact that there is now an INotifyDataErrorInfo interface which includes some of this added functionality. You can find out more from the INotifyDataErrorInfo Interface page on MSDN.
UPDATE >>>
Yes, the ExternalErrors property just let's me add errors that relate to a data object from outside that object... sorry, my example wasn't complete... if I'd have shown you the IsGenreNameUnique method, you would have seen that it uses LinQ on all of the Genre data items in the collection to determine whether the object's name is unique or not:
private bool IsGenreNameUnique(Genre genre)
{
return Genres.Where(d => d.Name != string.Empty && d.Name == genre.Name).Count() == 1;
}
As for your int/string problem, the only way I can see you getting those errors in your data class is if you declare all your properties as object, but then you'd have an awful lot of casting to do. Perhaps you could double your properties like this:
public object FooObject { get; set; } // Implement INotifyPropertyChanged
public int Foo
{
get { return FooObject.GetType() == typeof(int) ? int.Parse(FooObject) : -1; }
}
Then if Foo was used in code and FooObject was used in the Binding, you could do this:
public override string this[string propertyName]
{
get
{
string error = string.Empty;
if (propertyName == "FooObject" && FooObject.GetType() != typeof(int))
error = "Please enter a whole number for the Foo field.";
...
return error;
}
}
That way you could fulfil your requirements, but you'll have a lot of extra code to add.
In my opinion, the problem lies in validation happening at too many places. I also wished to write all my validation login in ViewModel but all those number binding were making my ViewModel crazy.
I solved this problem by creating a binding that never fails. Obviously, if a binding is always successful then the type itself has to handle the error conditions gracefully.
Failable Value Type
I started by creating a generic type which would gracefully support the failed conversions:
public struct Failable<T>
{
public T Value { get; private set; }
public string Text { get; private set; }
public bool IsValid { get; private set; }
public Failable(T value)
{
Value = value;
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
Text = converter.ConvertToString(value);
IsValid = true;
}
catch
{
Text = String.Empty;
IsValid = false;
}
}
public Failable(string text)
{
Text = text;
try
{
var converter = TypeDescriptor.GetConverter(typeof(T));
Value = (T)converter.ConvertFromString(text);
IsValid = true;
}
catch
{
Value = default(T);
IsValid = false;
}
}
}
Note that even if the type fails to initialise because of invalid input string (second constructor), it quietly stores the invalid state along with invalid text also. This is required in order to support the round-trip of binding even in case of wrong input.
Generic Value Converter
A generic value converter could be written using above type:
public class StringToFailableConverter<T> : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(Failable<T>))
throw new InvalidOperationException("Invalid value type.");
if (targetType != typeof(string))
throw new InvalidOperationException("Invalid target type.");
var rawValue = (Failable<T>)value;
return rawValue.Text;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value.GetType() != typeof(string))
throw new InvalidOperationException("Invalid value type.");
if (targetType != typeof(Failable<T>))
throw new InvalidOperationException("Invalid target type.");
return new Failable<T>(value as string);
}
}
XAML Handy Converters
Since creating and using the instances of generics is pain in XAML, lets make static instances of common converters:
public static class Failable
{
public static StringToFailableConverter<Int32> Int32Converter { get; private set; }
public static StringToFailableConverter<double> DoubleConverter { get; private set; }
static Failable()
{
Int32Converter = new StringToFailableConverter<Int32>();
DoubleConverter = new StringToFailableConverter<Double>();
}
}
Other value types can be extended easily.
Usage
Usage is pretty simple, just need to change the type from int to Failable<int>:
ViewModel
public Failable<int> NumberValue
{
//Custom logic along with validation
//using IsValid property
}
XAML
<TextBox Text="{Binding NumberValue,Converter={x:Static local:Failable.Int32Converter}}"/>
This way, you can use the same validation mechanism (IDataErrorInfo or INotifyDataErrorInfo or anything else) in ViewModel by checking the IsValid property. If IsValid is true, you can directly use the Value.
Ok, I believe I have found the answer you were looking for...
It will not be easy to explain - but..
Very easy to understand once explained...
I do think It is most accurate/"certified" to MVVM viewed as "standard" or at the least attempted standard.
But before we begin.. you need to change a concept which you got used to regarding MVVM:
"Furthermore it would change the semantics of the view model. For me,
a view is built for the view model and not the reverse—of course the design
of the view model depends on what we imagine the view to do,
but there’s still general freedom how the view does that"
That paragraph is the source of your problem.. - why?
Because you are stating the View-Model has no role to adjust itself to the View..
That is wrong in many ways - as I'll prove to you very simply..
If you have a property such as:
public Visibility MyPresenter { get...
What is Visibility if not something that serves the View?
The type itself and the name that will be given to the property is definitely made up for the view.
There two distinguishable View-Models categories in MVVM according to my experience:
Presenter View Model - which is to be hooked to buttons, menus, Tab Items etc....
Entity View Model - which is to be hocked to controls that brings the entity data to screen.
These are two different - completely different concerns.
And now to the solution:
public abstract class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public class VmSomeEntity : ViewModelBase, INotifyDataErrorInfo
{
//This one is part of INotifyDataErrorInfo interface which I will not use,
//perhaps in more complicated scenarios it could be used to let some other VM know validation changed.
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
//will hold the errors found in validation.
public Dictionary<string, string> ValidationErrors = new Dictionary<string, string>();
//the actual value - notice it is 'int' and not 'string'..
private int storageCapacityInBytes;
//this is just to keep things sane - otherwise the view will not be able to send whatever the user throw at it.
//we want to consume what the user throw at us and validate it - right? :)
private string storageCapacityInBytesWrapper;
//This is a property to be served by the View.. important to understand the tactic used inside!
public string StorageCapacityInBytes
{
get { return storageCapacityInBytesWrapper ?? storageCapacityInBytes.ToString(); }
set
{
int result;
var isValid = int.TryParse(value, out result);
if (isValid)
{
storageCapacityInBytes = result;
storageCapacityInBytesWrapper = null;
RaisePropertyChanged();
}
else
storageCapacityInBytesWrapper = value;
HandleValidationError(isValid, "StorageCapacityInBytes", "Not a number.");
}
}
//Manager for the dictionary
private void HandleValidationError(bool isValid, string propertyName, string validationErrorDescription)
{
if (!string.IsNullOrEmpty(propertyName))
{
if (isValid)
{
if (ValidationErrors.ContainsKey(propertyName))
ValidationErrors.Remove(propertyName);
}
else
{
if (!ValidationErrors.ContainsKey(propertyName))
ValidationErrors.Add(propertyName, validationErrorDescription);
else
ValidationErrors[propertyName] = validationErrorDescription;
}
}
}
// this is another part of the interface - will be called automatically
public IEnumerable GetErrors(string propertyName)
{
return ValidationErrors.ContainsKey(propertyName)
? ValidationErrors[propertyName]
: null;
}
// same here, another part of the interface - will be called automatically
public bool HasErrors
{
get
{
return ValidationErrors.Count > 0;
}
}
}
And now somewhere in your code - your button command 'CanExecute' method can add to its implementation a call to VmEntity.HasErrors.
And may peace be upon your code regarding validation from now on :)
The drawback is that this might run the validation on all properties a
bit too often, but most validations should be simply enough to not
hurt the performance. Another solution would be to remember which
properties produced errors using the validation and only check those,
but that seems a bit overcomplicated and unecessary for most times.
You don't need to track which properties have errors; you only need to know that errors exist. The view model can maintain a list of errors (also useful for displaying an error summary), and the IsValid property can simply be a reflection of whether the list has anything. You don't need to check everything each time IsValid is called, as long as you ensure that the error summary is current and that IsValid is refreshed each time it changes.
In the end, this is a problem of the view. The view (and its data
binding engine) is responsible for giving the view model proper values
to work with. But in this case, there seems to be no good way to tell
the view model that it should invalidate the old property value.
You can listen to errors within the container that is bound to the view model:
container.AddHandler(Validation.ErrorEvent, Container_Error);
...
void Container_Error(object sender, ValidationErrorEventArgs e) {
...
}
This notifies you when errors are added or removed, and you can identify binding exceptions by whether e.Error.Exception exists, so your view can maintain a list of binding exceptions and inform the view model of it.
But any solution to this problem will always be a hack, because the view is not filling its role properly, which is giving the user a means of reading and updating the view model structure. This should be seen as a temporary solution until you correctly present the user with some kind of "integer box" instead of a text box.
Here's an effort to simplify things if you don't want to implement tons of additional code...
The scenario is that you have an int property in your viewmodel (could be decimal or another non-string type) and you bind a textbox to it in your view.
You have validation in your viewmodel that fires in the setter of the property.
In the view a user enters 123abc and the view logic highlights the error in the view, but can't set the property because the value is the wrong type. The setter never gets called.
The simplest solution is to change your int property in the viewmodel to be a string property, and cast the values into and out of it from the model. This allows the bad text to hit the setter of your property, and your validation code can then check the data and reject it as appropriate.
IMHO validation in WPF is broken, as can be seen from the elaborate (and ingenious) ways people have tried to work around the problem given previously. For me I don't want to add a huge amount of extra code or implement my own type classes to enable a textbox to validate so basing these properties on strings is something I can live with, even if it does feel like a bit of a kludge.
Microsoft should look at fixing this so that the scenario of invalid user input in a textbox bound to an int or decimal property can somehow communicate this fact elegantly to the viewmodel. It should be possible, for instance for them to create a new bound property for a XAML control to communicate view logic validation errors to a property in the viewmodel.
Thanks and respect to the other guys that have provided detailed answers to this topic.
What's the right way to get my viewmodel to trigger a custom lookup control to throw up a modal dialog that essentially represents that lookup viewmodel? The custom lookup control's data context is that of the parent record view model. The lookup control also has another DependencyProperty that has it bound to a lookupviewmodel property on the parent record view model and this represents a sub lookupviewmodel.
METHOD 1) I currrently use an event on the lookupviewmodel that the custom control knows to listen for.
METHOD 2) I tried throwing a validation exception within the setter of the property on the lookupviewmodel that the lookup control's text propery is bound too. Then I hooked the ErrorEvent in the custom lookup control. But it seems that if the user "corrects" the value from within the dialog while in this event, the original value sticks. And worse, even after I call Validation.ClearInvalid, another ErrorEvent still fires that somehow adds the error back. So everything works here in the sense that all the viewmodels have the correct data, it's just that it seems like the textbox is ignoring that the bound text property has changed on the underlying data source when inside an ErrorEvent. So it seems like I can't correct an error while inside the processing of that error?
Another sub issue within method 2 is that Validation.ClearInvalid doesn't remove the red error border. I had to manually clear the ErrorTemplate too. Is that right?
I'd like to find a way to use natural error handling within the control to get it to throw up the modal dialog.
This isn't what you use events for. Events exist to facilitate decoupling: the object raising the event shouldn't know or care what the object(s) listening to it are doing. You're expecting an event to be able to change the value of a property from inside the property's setter - or worse, your event handler is calling the very property setter that's raising the event that it's handling, which means that you have to do something pretty hackish to avoid a stack overflow.
Your description isn't very clear (you're describing both the problem you're having and the non-working solutions you're trying at the same time, which is confusing), but it sounds like what you're trying to do is something more like:
if (IsValid(value))
{
_Property = value;
}
else
{
_Property = GetValueFromDialog();
}
The problem is that you don't want to have code in your view model that throws up a dialog, since that creates a view model that can't be tested outside of your WPF application.
The answer in this case is to use dependency injection. Create an interface called IDialogService:
interface IDialogService
{
object GetValueFromDialog();
}
Now add this property to your view model:
public IDialogService DialogService { get; set; }
The above code becomes:
if (IsValid(value))
{
_Property = value;
}
else
{
_Property = DialogService.GetValueFromDialog();
}
Create a dialog service for use in your WPF application that actually throws up the dialog and gets the result. When you instantiate your view model in your application, do this:
MyViewModel vm = new MyViewModel { DialogService = new WpfDialogService(); }
Thus, in your application, the property setter will put up the dialog and get the result exactly as you expect it to.
For your unit tests, create a mock dialog that looks like this:
public class MockDialogService : IDialogService
{
private object Result;
public MockDialogService(object result)
{
Result = result;
}
public object GetValueFromDialog() { return Result; }
}
You can then write a test like:
MyViewModel vm = new MyViewModel { DialogService = MockDialogService(ExpectedResult) };
vm.Property = InvalidValue;
Assert.AreEqual(ExpectedResult, vm.Property);
The above is really more a sketch of a solution than a solution - depending on how your application uses dialogs, you may need a lot more features than what are sketched out here. If you take a look at MVVM frameworks you'll find that a lot of them implement dialog services of one kind or another.
You can use a framework like MVVMLight or Prism which allow you to pass payloads between different entities in totally decoupled ways. MVVMLight is very lightweight compared to Prism. It has a concept of Messanger which acts as a system wide event bus. Similarly you have EventAggregator in Prism.
I'm developing a WinForms application in C#. I have limited experience in GUI programming, and I am having to learn a great deal on the fly. That being said, here's what I am building.
See the general GUI look at the following link:
GUI http://img227.imageshack.us/img227/1084/program0.jpg
Now, I have done a lot of the work already, but in the very bad Autonomous design pattern. I did not know the project would ever reach a certain size, and, as such, it is time to do some major refactoring.
I have been studying a great deal about GUI design patterns, and the pattern I am wishing to implement is the Passive View (see http://martinfowler.com/eaaDev/PassiveScreen.html). I am looking for some help on how to bring this all together.
Background:
1) Depending on what the user clicks in the "TreeView", the "List" in the bottom left-hand corner will display a list of objects that can populate the "Editor" area. These objects might be a TextBox or a DataGridView. The user toggles the List to choose what he/she wants to see in the "Editor"
2) The model is essentially a folder with data and configuration files. There is an external program that runs on a given directory, creates output files/folders, etc. This program I am developing is designed to effectively manage/configure these objects in a user-friendly way
3) The problem with the way I have been doing things is that it is next to impossible to test, and hence the move to the MVP-esque Passive View design pattern
I am trying to make it so that the program works independently of the View. I have not been able to find any examples where a more complex, interactive view is used with the Passive View pattern.
Questions:
1) Do I need to implement one large interface/view for the entire "look" of the program, then implement sub-interfaces/sub-views for each of the TreeView, Editor, Logger, etc.? Or is there a better "structure" to doing this?
2) When it comes to "handing off" events from the View to the Presenter/Controller (whatever terminology you wish to use W.R.T. the Passive View design pattern), what is the way I should be doing this? Sometimes I have simple properties that need to be updated, and sometimes I need a whole series of steps to unfold.
I would love suggestions and advice on this topic. I have scoured the Internet, and I haven't found adequate examples to help me continue with this project.
Thanks in advance!
Daniel
Here is a simple example that demonstrates the concept of passive views using the MVP design pattern. Because we are using passive views the view has no knowledge of the presenter. The presenter will simply subscribe to events published by the view and act accordingly.
To start out we need to define a contract for our view. This is typically achieved using an interface, essentially, we want to have a very loose coupling with our view. We want the ability to switch to different views or event create mock views for unit testing.
Here is a contract that describes a simple view that will be used to display customer information
public interface ICustomerManagementView
{
void InitializeCustomers(ICustomer[] customers);
void DisplayCustomer(ICustomer customer);
event EventHandler<EventArgs<ICustomer>> SelectedCustomerChanged;
}
It exposes a single method InitializeCustomers that will be used to initialize our view with objects from our model.
We also have an event SelectedCustomerChanged that will be used by our presenter to receive notification that an action has occurred in the view.
Once we have our contract we can start to handle these interactions in our presenter.
public class CustomerManagementPresenter
{
private ICustomer _selectedCustomer;
private readonly ICustomerManagementView _managementView;
private readonly ICustomerRepository _customerRepository;
public CustomerManagementPresenter(ICustomerManagementView managementView, ICustomerRepository customerRepository)
{
_managementView = managementView;
_managementView.SelectedCustomerChanged += this.SelectedCustomerChanged;
_customerRepository = customerRepository;
_managementView.InitializeCustomers(_customerRepository.FetchCustomers());
}
private void SelectedCustomerChanged(object sender, EventArgs<ICustomer> args)
{
// Perform some logic here to update the view
if(_selectedCustomer != args.Value)
{
_selectedCustomer = args.Value;
_managementView.DisplayCustomer(_selectedCustomer);
}
}
}
In the presenter we can use another design pattern called dependency injection to provide access to our view and any model classes that we may need. In this example I have a CustomerRepository that is responsible for fetching customer details.
In the constructor we have two important lines of code, firstly we have subscribed to the SelectedCustomerChanged event in our view, it is here that we can perform associated actions. Secondly we have called InitilaizeCustomers with data from the repository.
At this point we haven't actually defined a concrete implementation for our view, all we need to do is create an object that implements ICustomerManagementView. For example in a Windows Forms application we can do the following
public partial class CustomerManagementView : Form, ICustomerManagementView
{
public CustomerManagementView()
{
this.InitializeComponents();
}
public void InitializeCustomers(ICustomer[] customers)
{
// Populate the tree view with customer details
}
public void DisplayCustomer(ICustomer customer)
{
// Display the customer...
}
// Event handler that responds to node selection
private void CustomerTreeViewAfterSelect(object sender, TreeViewEventArgs e)
{
var customer = e.Node.Tag as ICustomer;
if(customer != null)
{
this.OnSelectedCustomerChanged(new EventArgs<ICustomer>(customer));
}
}
// Protected method so that we can raise our event
protected virtual void OnSelectedCustomerChanged(EventArgs<ICustomer> args)
{
var eventHandler = this.SelectedCustomerChanged;
if(eventHandler != null)
{
eventHandler.Invoke(this, args);
}
}
// Our view will raise an event each time the selected customer changes
public event EventHandler<EventArgs<ICustomer>> SelectedCustomerChanged;
}
If we wanted to test our presentation logic we could mock our view and perform some assertions.
EDIT : Included custom event args
public class EventArgs<T> : EventArgs
{
private readonly T _value;
public EventArgs(T value)
{
_value = value;
}
public T Value
{
get { return _value; }
}
}
I would break them down into separate views with their own presents, and use a "controlling" presenter / view to manage message delegation between them all. Not only will this aid testability but it'll keep your controls fulfilling SRP, too.
So in your case you might have an IFormManager which your main window will implement, and then an IFileManager, ILoggerWindow etc. etc.
Although it might be a bit overkill to use, I would suggest that you have a look at Smart Client Software Factory (from the Microsoft Patterns and Practices team) - it's not being actively developed any more, but it has a good implementation of MVP and does this sort of view composition stuff quite well, so might give you some good ideas.
My question is : how to move beyond writing a custom implementation of a technique for databinding multiple controls (controls without built-in DataSource properties), for each possible type of data, to simple properties ... as described and demonstrated in code that follows ... to achieve a more poweful solution that will be independent of whether the binding is to a string, or an int, or other types.
My guess is: this will involve reflection; but, I'm stuck at that point. I'm looking for strategic advice on which "direction" to move next, hints, clues, not a complete code answer, but of course I appreciate all responses, and I'll sure study code if you post code in reply ! Marc Clifton's 2005 article on CodeProject Simple Databinding: appears to demonstrate a reflection based approach: but, honestly, I do not really grok his code, and, in terms of .NET, 2005 is a long time ago.
Background: Partly in response to various SO questions and answers, like: Update Usercontrol on Three Forms: I've evolved a successful technique for databinding text properties of various controls simultaneously to one source defined in a Public class; also been able to "abstract" some of the details of the binding process using a static class that defines one extension method, and two public methods.
I've verifed that TextBoxes on Controls in a "MainForm," TextBoxes on a UserControl on the MainForm, and a TextBox on a second Form opened "independently" (i.e., form2.Parent == null) all update properly (i.e., two-way binding is in effect) from the "DataSource equivalent" public class. Change one: change all.
Code: an instance of this class will supply the target property (theText) for databinding:
public class TextDataBinder
{
public event PropertyChangedEventHandler PropertyChanged;
private string _theText;
public string theText
{
get { return _theText; }
// note : if 'setter is declared 'internal : blocks
// auto-updating when run-time user modifies consumers
// but will still allow update via code
set
{
_theText = value;
OnPropertyChanged(new PropertyChangedEventArgs("theText"));
}
}
protected void OnPropertyChanged(PropertyChangedEventArgs e)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, e);
}
}
}
Code: this static class enables hiding some of the binding process complexity, and allows easy binding to multiple controls:
public static class TextBindingExtender
{
public static TextDataBinder CurrentDataSource;
public static void SetCurrentDataSource(TextDataBinder newCurrentDataSource)
{
CurrentDataSource = newCurrentDataSource;
}
// extension method for Control
public static void AddTextBinding(this Control theControl, string controlPropertyName, string targetPropertyName)
{
theControl.DataBindings.Add(controlPropertyName, CurrentDataSource, targetPropertyName, false, DataSourceUpdateMode.OnPropertyChanged);
}
// bind to all Controls in a List<Control>
public static void AddTextBindings(List<Control> theControls, string controlPropertyName, string targetPropertyName)
{
foreach (Control theControl in theControls)
{
theControl.AddTextBinding(controlPropertyName, targetPropertyName);
}
}
}
How the above classes are used (in a Form Load event) :
// create a new TextDataBinder
TextBindingExtender.CurrentDataSource = new TextDataBinder();
// bind to multiple textboxes, label, on a UserControl, on another Form, etc.
TextBindingExtender.AddTextBindings(new List<Control> { textBox1, textBox2, userControl11.tb, label1, instanceOfForm2.tb }, "Text", "theText");
// test assigning some initial text to the bound property
TextBindingExtender.CurrentDataSource.theText = "some initial text";
It really depends what you want to do; but ultimately common data-binding (for simple properties, done manually) consists of:
obtaining a property; preferably via TypeDescriptor.GetProperties(obj)[propName], giving you an abstraction (PropertyDescriptor)
asking the property if it is read-only (.IsReadOnly)
obtain (or set) the value (.GetValue(), .SetValue())
asking it for a converter to format / parse the value (.Converter, .ConvertFromString(), .ConvertToString()) THIS is a key bit that means you don't have to worry about what the data type is
asking it for the caption (.DisplayName, or .Name if that it empty/null)
asking it if it supports property-specific notification (.SupportsChangeEvents)
asking it to add/remove a change handler (.AddValueChanged(), .RemoveValueChanged())
you might also want to look at whether the object supports centralised notification (look for INotifyPropertyChanged)
If you might be binding to a list rather than a single object:
- the list might be abstracted behind IListSource
- the list might have custom properties, so check for ITypedList
- otherwise, identify the Type of the items and use TypeDescriptor.GetProperties(type)
- you need to consider a "currency manager" (i.e. should all the things bound to the same list be pointing to the same record in the list all the time)
There are also things like ICustomTypeDescriptor and TypeDescriptionProvider to consider, but most of the time TypeDescriptor handles this for you automatically.
As you can see - lots of things to think about! Lots of work... the one thing that you don't have to do is reflection; this is abstracted behind PropertyDescriptor. The reason for this is that not all data is static-typed; think about DataTable - the columns (which map to bindable data properties) are not fixed at compile-time, so reflection isn't appropriate. Likewise, some other types have custom "property bag" implementations. PropertyDescriptor lets your code handle either dynamic (not in the 4.0 sense) and reflective properties identically. It also works nicely with things like "HyperDescriptor", another property customisation.