Reputation: 3519
I just want to create a slider in my C# WPF project and write the value of the slider into a label. I know this is probably really easy to do but I can't manage to get it working. So here is my slider in my XAML code:
<Slider Height="21" Minimum="-255" Maximum="255" x:Name="sld_brightness" />
<Label x:Name="lb_brightness_nb" />
Now, I try to change the value of the label according to the slider value in my C# code:
public void sld_brightness_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
lb_brightness_nb.Content = (int)sld_brightness.Value;
}
This code does compile but doesn't do anything. It is not working. What's wrong?
Upvotes: 0
Views: 3027
Reputation: 102793
You could bind it directly; there's no need to create an event handler for this.
<Slider Height="21" Minimum="-255" Maximum="255" x:Name="sld_brightness" />
<Label x:Name="lb_brightness_nb"
Content="{Binding ElementName=sld_brightness,Path=Value,Converter={StaticResource DoubleToStringConverter}}" />
If you want to use the event handler, then it looks like you're missing the wireup:
<Slider Height="21" Minimum="-255" Maximum="255" x:Name="sld_brightness"
ValueChanged="sld_brightness_ValueChanged" />
Edit
To show only the integer, use an IValueConverter
. Add it to the resources section using <local:DoubleToStringConverter x:Key="DoubleToStringConverter" />
.
public class DoubleToStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return Math.Round((double)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
Upvotes: 3
Reputation: 2992
I can see the name of the label is lb_brightness_nb then lb_brightnessValue. You can change the name of it to compile.
Your code should look like :
public void sld_brightness_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
lb_brightness_nb.Content = sld_brightness.Value;
}
Let me know if that is what you are talking or something else.
Upvotes: 0