Is it possible to coerce the UpDown value?

2 posts, 0 answers
  1. Joe
    Joe avatar
    94 posts
    Member since:
    Nov 2017

    Posted 14 Nov 2019 Link to this post

    I'm wondering if you can suggest an approach to achieve an effect I want (which I describe below).  I don't think so but I thought I would check.

    I'm using a NumericUpDown to show length values of type double.    I want to be able to make the Up/Down buttons change the displayed value to an even multiples of a a whole number, regardless of the starting value or the direction (up vs down)  of the button they hit.  Is there a way to do this?

    For example, suppose the initial value is 1.23.   

    If the user hits the "Up" button, I want the value to change from 1.23 to 2.00. But the next time he/she hits it I want it to change from 2.00 to 3.00
    But if the user hits the "Down" button, I want the value to change from 1.23 to 1.00.  The next time, I want it to change from 1.00 to 0.00

    If there were separate "SmallChange" properties for the up and down directions, this would be easy.   I could bind them and do the math whenever the value changes.  But I only have the one "SmallChange" property.

    If there were some way for me to insert a "CoerceValue" callback into the "Value" property, I could do that.  But I don't believe that is possible.  If it is, please tell me how

    Is there any way to achieve this?

  2. Dimitar Dinev
    Dimitar Dinev avatar
    72 posts

    Posted 15 Nov 2019 Link to this post

    Hi Joe,

    Thank you for the description.

    You can achieve this behavior by implementing custom logic in the setter of the property you have bound to the Value property. Please, take a look at the following code snippet which checks if the value is a whole number:

    privatedouble boxValue = 1.23; publicdouble BoxValue { get { return boxValue; } set { var isIncreasing = value > this.boxValue; if (isIncreasing) { boxValue = (int)value; } else { if (!(this.boxValue == Math.Truncate(boxValue))) { this.boxValue = Math.Truncate(boxValue); } else { this.boxValue = boxValue - 1; } } OnPropertyChanged("BoxValue"); } }

    Attached, you can find a sample project demonstrating this approach. Please, review it and let me know if it delivered the desired result.

    Dimitar Dinev
    Progress Telerik

    Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Back to Top