Search code examples
wpfdata-bindingtypessliderconverters

Slider Minimum / Maximum binding to Int constant


I have an integer constants to define minimum and maximum values of some integer data, and i want to bind them to a Slider control properties like im doing on another numeric editor, but seems impossible.

Is there any easy way to acomplish this? Maybe with value converters, or Im missing something?

A bit of example code:

public const Int32 EXAMPLE_MIN_VALUE = 23;
public const Int32 EXAMPLE_MAX_VALUE = 55;

This works ok, im using an integer editor of WpfToolkit:

<WpfToolkit:IntegerUpDown Value="{Binding ExampleValue}" 
    Minimum="{x:Static Model:Configuracion.EXAMPLE_MIN_VALUE}" 
    Maximum="{x:Static Model:Configuracion.EXAMPLE_MAX_VALUE}" />

But when I try the same with Slider, it crash:

<Slider Value="{Binding ExampleValue}" 
    Minimum="{x:Static Model:Configuracion.EXAMPLE_MIN_VALUE}" 
    Maximum="{x:Static Model:Configuracion.EXAMPLE_MAX_VALUE}" />

Solution

  • If you use x:Static directly that has no room for type conversion and thus causes an exception as you try to set an int on a double-property, but if you do this it works just fine:

    Minimum="{Binding Source={x:Static local:MainWindow.TestConstInt}}"
    

    That is because bindings apply type converters where necessary. And even if there were no suitable type converter you could just add a Binding.Converter.