Slider's behaviour depending on minimum-maximu

2019-07-20 02:57发布

I'm working on Windows Phone 8.1 Runtime and I've encountered strange problem.

Let's define two almost identical Silders:

<Slider Header="Values 0.1-0.9" Grid.Row="0" HorizontalAlignment="Stretch" TickFrequency="0.05" TickPlacement="Inline"
        Minimum="0.1" Maximum="0.9" Value="0.2"/>
<Slider Header="Values 1.0-9.0" Grid.Row="1" HorizontalAlignment="Stretch" TickFrequency="0.5"  TickPlacement="Inline"
        Minimum="1" Maximum="9" Value="2"/>

As you can see the second Slider differentiate from the first only by it's range (10 times). But it turns out that the first one is not working properly (see attached image) - the value seems to be starting from 0 (thought you cannot set it below the set minimum 0.1 - you always have little horizontal track from 0).

It seems to be a little bug (probably with rounding the minimum value somewhere?), but maybe I've missed something. Is there a way to make it work with values less than 1.0 (without using Converters)?

sliders

1条回答
你好瞎i
2楼-- · 2019-07-20 03:22

An interesting problem you have found there. +1 for the question.

I checked it our and it seems the built-in Slider really doesn't work very well when Minimum and Maximum are not whole numbers. I can think of 3 ways to work-around this.

1. Add wrapper Property to the VM class (I assume you want to bind the Value, since you mentioned Converters)

The idea is to add another Property to the VM that you bind to like this:

//Lets assume that the original property that ranges from 0.1 to 0.9 is called MyProp
public double MyPropBinding {
    get {
        return this.MyProp * 10.0;
    }
    set {
        this.MyProp = value / 10.0;
    }
}

This is basically quite simple and requires no additional class, which is my biggest problem with converters. It may not be perfect if you have 10 VM classes that need to do it, though.

2. Using a Converter

Yes, I know you asked for an option without a Converter, but I wanted to say that it is actually a very good option. Not super cool as you need another class and longer binding text, but does not require any research. And time is precious! You can basically solve your problem in a few minutes in a non-hacky way.

3. Fixing the Slider (one way or another)

I think you could extend the Slider and add some properties to it, that will fix it. For example: Scale (that would be 10 in your case) and ValueScaled which would be Value / Scale. So you would be using your custom Slider, Min and Max would be 1 and 9, Scale would be 10 and you'll have ValueScaled which would be the value that you actually want.

P.S. I haven't researched it a lot, because I think at least one of these should work just fine for you (and everyone else). There may be cooler solutions out there. :)

查看更多
登录 后发表回答