Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF how to bind slider's value to label's content with StringConverter?

I have a simple slider and a plain label. Label's content is bound to slider's value and it works fine- when you move the slider , label's content changes e.g 23.3983928394 , 50.234234234 and so on

I'd like to round it to int values. 1,2,10....100 . But when I try to use a converter I get the "ivalueconverter does not support converting from a string".

How can I convert the slider's Value to an int in the converter?

Thank you

This is my XAML

<Grid.Resources>
        <local:MyConvertor x:Key="stringconverter" />
    </Grid.Resources>
<Slider x:Name="mySlider" Height="50" Width="276" Maximum="100"/>
<Label Content="{Binding ElementName=mySlider, Path=Value, Converter=stringconverter}" />

This is my stringconverter class

public class MyConvertor: IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //How to convert string to int?
    }
like image 472
iAteABug_And_iLiked_it Avatar asked Jul 11 '13 21:07

iAteABug_And_iLiked_it


4 Answers

You could just use the StringFormat property here instead of creating a converter. The double value will be rounded to an int due to the # format specified.

<TextBlock Text="{Binding ElementName=mySlider, Path=Value, StringFormat={}{0:#}}"/>

If you want to keep the label, instead of using a TextBlock, you can use ContentStringFormat instead as Content takes in an object type.

<Label Content="{Binding ElementName=mySlider, Path=Value}" ContentStringFormat="{}{0:#}" />
like image 95
keyboardP Avatar answered Nov 17 '22 04:11

keyboardP


To answer the question: the error is thrown because of

Converter=stringconverter

it has to be

Converter={StaticResource stringconverter}

In your converter you convert not string to int but double (Slider.Value) to object (Label.Content) which can be a string too. e.g.

return ((double)value).ToString("0");

or

return Math.Round((double)value);
like image 25
LPL Avatar answered Nov 17 '22 03:11

LPL


you can use the Label's ContentStringFormat property

<Label Content="{Binding ElementName=Slider, Path=Value}" 
   ContentStringFormat="{}{0:N0}" />
like image 2
Erwin Draconis Avatar answered Nov 17 '22 02:11

Erwin Draconis


Check the Slider's IsSnapToTickEnabled property

like image 1
ChuckMorris42 Avatar answered Nov 17 '22 03:11

ChuckMorris42