[英]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. 我只想在C#WPF项目中创建一个滑块并将滑块的值写入标签中。 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: 所以这是我的XAML代码中的滑块:
<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: 现在,我尝试根据C#代码中的滑块值更改标签的值:
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
. 要仅显示整数,请使用IValueConverter
。 Add it to the resources section using <local:DoubleToStringConverter x:Key="DoubleToStringConverter" />
. 使用<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. 我可以看到标签的名称是lb_brightness_nb,然后是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. 让我知道你在说什么还是其他。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.