Hello,
i'm trying to implement the validation in MVVM WPF C# application.
In the MVVM Pattern, is it better to implement the validation (with IDataErrorInfo) in the Model o in the ViewModel?
What I have tried:
At the moment i've implement the validation inside the Model part.
ViewModel:
private Order selectedOrder;
public Order SelectedOrder
{
get
{
return selectedOrder;
}
set
{
selectedOrder= value;
OnPropertyChanged("SelectedOrder");
}
}
as part of the model i have the definition of the class Order:
public class Order : Notifier, IDataErrorInfo
{
private string _NumOrder = "";
public string NumOrder
{
get
{
return _NumOrder;
}
set
{
_NumOrder = value;
OnPropertyChanged("NumOrder");
}
}
#region IDataErrorInfo
string IDataErrorInfo.Error
{
get
{
return null;
}
}
string IDataErrorInfo.this[string propertyName]
{
get
{
return GetValidationError(propertyName);
}
}
#endregion
#region Validation
static readonly string[] ValidateProperty =
{
"NumOrder"
};
public bool IsValid
{
get
{
foreach(string property in ValidateProperty)
if (GetValidationError(property) != null)
return false;
return true;
}
}
public string ValidateOrder()
{
if (String.IsNullOrWhiteSpace(numOrder))
{
return "Error, i need a value";
}
return null;
}
string GetValidationError(String propertyName)
{
string error = null;
switch (propertyName)
{
case "NumOrder":
error = ValidateOrder();
break;
}
return error;
}
#endregion
}
In the View i'm trying to display the error, but it doesn't work.
<TextBox x:Name="txtNumOrder" FontSize="14" IsEnabled="{Binding ActionInRun,ConverterParameter=NumOrder, Converter={StaticResource EnumToBoolean}}" Text="{Binding SelectedOrder.numOrder, Mode=TwoWay, ValidatesOnDataErrors=True, UpdateSourceTrigger=PropertyChanged}"/>
<Label FontSize="12" x:Name="lblNote" Content="{Binding ElementName=numOrder, Path=(Validation.Errors).CurrentItem.ErrorContent}" />
Because in the textbox field the validation works correctly, but the label don't show the error message.
How can i display the error correctly?
Thanks in advance