WPF how to bind a slider value to label content using StringConverter?

I have a simple slider and simple shortcut . The contents of the label are tied to the value of the slider, and it works great when moving the slider, changing the contents of the label, for example, 23.3983928394, 50.234234234, etc.

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

How to convert slider value to int in converter?

thanks

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? } 
+4
source share
4 answers

To answer the question: the error is caused due to

 Converter=stringconverter 

he should be

 Converter={StaticResource stringconverter} 

In the converter, you do not convert a string to int, but double ( Slider.Value ) to an object ( Label.Content ), which can also be a string. eg.

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

or

 return Math.Round((double)value); 
+3
source

You can simply use the StringFormat property instead of creating a converter. A double value will be rounded to an int value due to the specified # format.

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

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

 <Label Content="{Binding ElementName=mySlider, Path=Value}" ContentStringFormat="{}{0:#}" /> 
+16
source

you can use the Label property ContentStringFormat

 <Label Content="{Binding ElementName=Slider, Path=Value}" ContentStringFormat="{}{0:N0}" /> 
0
source

Check Slider IsSnapToTickEnabled Property

0
source

Source: https://habr.com/ru/post/1491017/


All Articles