简体   繁体   中英

How do I Reset value of IntegerUpDown to minimum if it exceeds maximum

I have IntegerUpDown like this

<xctk:IntegerUpDown Value ="{Binding SomeValue}", Maximum="2" Minimum="0"/>. 

I was if the value is - SomeValue == 2 (Maximum) . I want to set SomeValue = 0 (Minimum) when I click on arrow up in Control.

How can I do that?

If you want to do it on View side, for simple dirty solution you might want to try handle ValueChanged event and check there if minimum or maximum is reached. It probably won't allow you to change value when you reach your maximum/minimum, so you probably want to set your values to <xctk:IntegerUpDown Value ="{Binding SomeValue}", Maximum="3" Minimum="-1"/>. and change it accordingly to 0 or 2 if it's reached.

For a better and cleaner solution, I am not sure what others events are raised when you try to change value beyond maximum/minimum. But you could create a control based on IntegerUpDown and override int IncrementValue(int value, int increment) and int DecrementValue(int value, int increment) methods.

You can use the Value changed event to get the current value. At the Value changed event, check for the value, if it is equal to Maximum, set it to Minimum as follows:

private void IntegerUpDown_ValueChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        var updown = (sender as IntegerUpDown);
        if (updown.Value == updown.Maximum)
            updown.Value = updown.Minimum;
    }

If you are using MVVM, then use interaction behavior or command to do the same.

or may be, you would bind the Value to a property in your ViewModel, as like you can bind the Max, Min Value to properties in ViewModel. And you can check the value at the property changed event of Value property, and can set the Value on goes above the Maximum value property.

You could also remove the min/max limits in the xaml:

<xctk:IntegerUpDown Value ="{Binding SomeValue}" />

And then handle the min/max limiting and rollover in your view model:

public double SomeValue
{
    get { return _SomeValue; }
    set
    {
        if (value < 0)
            _SomeValue = 0;
        else if (value >= 2)
            _SomeValue = 0;
        else
            _SomeValue = value;
        OnPropertyChanged("SomeValue");
    }
}
private double _SomeValue = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM