How do I handle DependencyProperty overflow situations?

前端 未结 1 480
小蘑菇
小蘑菇 2020-12-11 13:57

I have a UserControl and an int DependencyProperty called Value. This is bound to a text input on the UserControl.

pu         


        
相关标签:
1条回答
  • 2020-12-11 14:19

    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/

    0 讨论(0)
提交回复
热议问题