Check for Valid Values between two DecimalUpDown C

2019-03-04 01:08发布

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.

enter image description here

Notice that the red values are wrong one.

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

Thank you. Steve

标签: c# wpf xaml mvvm
3条回答
在下西门庆
2楼-- · 2019-03-04 01:45

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.

查看更多
疯言疯语
3楼-- · 2019-03-04 01:46

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

查看更多
Ridiculous、
4楼-- · 2019-03-04 01:54

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

查看更多
登录 后发表回答