简体   繁体   中英

Sliders in a C# WPF project

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?

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();
    }
}

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;
}
  • you dont need to convert the Value to int as well.

Let me know if that is what you are talking or something else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM