Reputation: 859
how to write a custom setter for a dependency object in wpf using mvvm ?
In my ViewModel I have a dependency object called Seasonalprop which I use to bind to a TextBox in XAML. I would like to write a custom setter, so that it notifies the user when the provided string input cannot be converted to double. The error that I am getting is that value is a string and cannot be converted to double.
public double Seasonalprop
{
get { return (double)GetValue(SeasonalProperty); }
set
{
try
{
Double.TryParse(value, out parsedouble);
SetValue(SeasonalProperty, value);
}
catch(Exception ex)
{
MessageBox.Show(" String Input cannot be converted to
type double");
}
}
}
Upvotes: 0
Views: 129
Reputation: 1883
I think your whole concept was gone to a wrong direction. First of all, when a binding expression updates a dependency property, it will call its onwer's SetValue
method but not its clr property wrapper. So a custom setter would do nothing for you in this situation. And as @peeyushsingh's answer, wpf has binding validation for this. So, something you need should be like:
<TextBox Text="{Binding Seasonalprop, ValidatesOnExceptions=True}">
<Validation.ErrorTemplate>
<ControlTemplate>
<StackPanel Orientation="Horizontal">
<Border BorderThickness="1" BorderBrush="Red" >
<AdornedElementPlaceholder/>
</Border>
<TextBlock Foreground="Red" Margin="2" Name="cc"
Text="! Not a double."/>
</StackPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
Upvotes: 0
Reputation: 1407
I think you want to write a custom settor so that it notifies the user if the value in text box is invalid.
Have a look at the docs for validation in WPF
The text content of the TextBox in the following example is bound to the Age property (of type int) of a binding source object named ods. The binding is set up to use a validation rule named AgeRangeRule so that if the user enters non-numeric characters or a value that is smaller than 21 or greater than 130, a red exclamation mark appears next to the text box and a tool tip with the error message appears when the user moves the mouse over the text box.
Upvotes: 2