Combining ValidationRule and Value Converters for a text field

I have a simple problem that I just cannot find a good solution to. I have a text box associated with a double property value. The user can enter values ​​in the text field, but I only want to allow values ​​from 0 to 100. I would like to show a red border around the text field if an invalid value is entered while the text field still has focus (UpdateSourceTrigger = "PropertyChanged"). If the user clicks in the text box, I want to pin this value using the value converter to UpdateSourceTrigger = "LostFocus".

It is easy to make either a validation rule or a converter, but I cannot combine them, because I want the verification to be triggered on UpdateSourceTrigger = "PropertyChanged", and the converter should run on UpdateSourceTrigger = "LostFocus". Unfortunately, I can only select one or the other when setting up the binding on my TextBox.Text.

Any good ideas on how I could implement this functionality?

thank

/ Peter

+3
source share
1 answer

This is an interesting question. I'm not sure that I have a complete solution, but I would like to throw out a couple of ideas.

, TextBox? : MinValue MaxValue. OnLostFocus. ( : .)

public class NumericTextBox : TextBox
{
    public static readonly DependencyProperty MinValueProperty =
        DependencyProperty.Register("MinValue", typeof(double), typeof(NumericTextBox), new UIPropertyMetadata(Double.MinValue));

    public static readonly DependencyProperty MaxValueProperty =
        DependencyProperty.Register("MaxValue", typeof(double), typeof(NumericTextBox), new UIPropertyMetadata(Double.MaxValue));

    public double MinValue
    {
        get { return (double)GetValue(MinValueProperty); }
        set { SetValue(MinValueProperty, value); }
    }

    public double MaxValue
    {
        get { return (double)GetValue(MaxValueProperty); }
        set { SetValue(MaxValueProperty, value); }
    }

    protected override void OnLostFocus(System.Windows.RoutedEventArgs e)
    {
        base.OnLostFocus(e);

        double value = 0;

        // Parse text.
        if (Double.TryParse(this.Text, out value))
        {
            // Make sure the value is within the acceptable range.
            value = Math.Max(value, this.MinValue);
            value = Math.Min(value, this.MaxValue);
        }

        // Set the text.
        this.Text = value.ToString();
    }
}

, UpdateSourceTrigger = PropertyChanged .

, , .

  • , , , , . (, OnTextChanged .)
  • , , -, .
0

Source: https://habr.com/ru/post/1793463/


All Articles