I have a UserControl
and an int DependencyProperty
called Value. This is bound to a text input on the UserControl
.
pu
A int
property can never be set to something else than an int
value. The type of the Text property of a TextBox is however string
and the error occurs when when the runtime is trying to set your int
property to a string
value that doesn't represent a valid integer.
Your dependency property cannot do much about this as it never gets set. As @@Ed Plunkett suggests in his comment you could use a ValidationRule to do something before the value conversion occurs and present an error message to the user if the conversion fails:
public class StringToIntValidationRule : ValidationRule
{
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
int i;
if (int.TryParse(value.ToString(), out i))
return new ValidationResult(true, null);
return new ValidationResult(false, "Please enter a valid integer value.");
}
}
<TextBox>
<TextBox.Text>
<Binding Path="Value" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:StringToIntValidationRule ValidationStep="RawProposedValue"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Please refer to the following blog post about data validation in WPF for more information: https://blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/