Check for Valid Values between two DecimalUpDown C

2019-03-04 00:58发布

问题:

I have two DecimalUpDown Controls in my Window. One should show the maximum Value the other one minimum Value of the TextBox. The minimum control can not have greater values than the maximum one and vice versa.

Notice that the red values are wrong one.

How can I implement this? I am using the MVVM pattern.

Thank you. Steve

回答1:

You should implement the validation logic in your view model:

public class MyViewModel : IDataErrorInfo
{
    private int _min;
    public int Min
    {
        get { return _min; }
        set { _min = value; }
    }

    private int _max;
    public int Max
    {
        get { return _max; }
        set { _max = value; }
    }

    public string Error { get { return null; } }

    public string this[string columnName]
    {
        get
        {
            switch(columnName)
            {
                case "Min":
                    if (_min > _max)
                        return "Min cannot be greater than Max";
                    break;
                case "Max":
                    if (_max < _min)
                        return "Max cannot be smaller than Min";
                    break;
            }

            return null;
        }
    }
}

XAML:

<xctk:IntegerUpDown Value="{Binding Min,ValidatesOnDataErrors=True}" />
<xctk:IntegerUpDown Value="{Binding Max,ValidatesOnDataErrors=True}" />

Please refer to the following blog post for more information about how data validation in WPF works: https://blog.magnusmontin.net/2013/08/26/data-validation-in-wpf/.

You basiclly implement either the IDataErrorInfo or the newer INotifyDataErrorInfo in your view model.



回答2:

as I understand you need to compare max and min values in setters of your VM properties



回答3:

You can use onChange event from the text box . (select your textBox and check the event window you will find all events)

Wen change => compare value if error => show message



标签: c# wpf xaml mvvm