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?
}
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:#}" />
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);
you can use the Label's ContentStringFormat property
<Label Content="{Binding ElementName=Slider, Path=Value}"
ContentStringFormat="{}{0:N0}" />
Check the Slider's IsSnapToTickEnabled property
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With