Reputation: 19356
Well, by the moment I am validating data on my way. I have this code:
In my view:
<TextBox Height="23" Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left" Margin="257,150,0,0" Name="txtAge" VerticalAlignment="Top" Width="54"
Visibility="{Binding AgeVisibility}"
IsEnabled="{Binding AgeIsEnabled}"
ToolTip="{Binding AgeToolTip}"
ToolTipService.ShowOnDisabled="true">
<TextBox.Style>
<Style TargetType="TextBox">
<Style.Triggers>
<DataTrigger Binding="{Binding ElementName=ucPrincipal, Path=DataContext.AgeCorrect}" Value="false">
<Setter Property="Background" Value="{StaticResource ResourceKey=TextBoxIncorrectValue}"/>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBox.Style>
</TextBox>
In my view model:
private bool _ageCorrect = true;
public bool AgeCorrect
{
get { return _ageCorrect; }
set
{
_ageCorrect = value;
base.RaisePropertyChangedEvent("AgeCorrect");
}
}
private string _ageToolTip = "";
public string AgeToolTip
{
get { return _ageToolTip; }
set
{
_ageToolTip = value;
base.RaisePropertyChangedEvent("AgeToolTip");
}
}
private void validateAge()
{
decimal decParsedAge;
if(decimal.TryParse(Age, out decParsedAge) == true)
{
if (decParsedAge <= 0)
{
AgeToolTip = "Age must be greater than 0";
AgeCorrect = false;
}
else
{
AgeCorrect = true;
}
}
else
{
AgeToolTip = "Age must be a decimal number.";
AgeCorrect = false;
}
}
That works fine. However I am seeing some examples about the IDataErrorInfo, but really if I want a bit complex data validation, from my point of view, the code is not very different. So I am wondering if it worths to change my code to implement the IDataErrorInfo interface.
Thank so much.
Upvotes: 2
Views: 105
Reputation: 3799
If you need to display more verbose validation (other than the exceptions thrown from the view model), then implementing IDataErrorInfo in my view is a good starting point and easy to extend your view model with; just requiring two members: a string property named Error and a string indexer.
The Error property provides an overall error string that describes the entire object (which could be something as simple as “Invalid Data”). The string indexer accepts a property name and returns the corresponding detailed error information. For example, if you pass an “Age” property to the string indexer, you might receive a response such as “The age cannot be negative.”
Quoting Matthew MacDonald, "the key idea here is that properties are set normally, without any fuss, and the indexer allows the user interface to check for invalid data".
Upvotes: 1