How to get and bind the value of Slider in C# WPF?
33,361
When I just want to set the value of my sliders as content of a Label, I simply go with this:
<Label Content="{Binding ElementName=mySlider, Path=Value}"/>
When you want to show the value as an integer you just have to save your value everytime your slider changes its value.
<Slider Name="mySlider" ValueChanged="SliderValueChanged" />
...
this.sliderValue = (int) mySlider.Value;
Then bind the content of your label to it.
Author by
Samet
Updated on October 17, 2020Comments
-
Samet over 3 years
I can get the value of slider here:
public void TheSlider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { int k = (int)TheSlider.Value; Debug.WriteLine(k); }
In this part, I cant get the value, so I cant use it :
private void Window_Loaded(object sender, RoutedEventArgs e) { _runtime.NuiCamera.ElevationAngle = (int)TheSlider.Value; }
This is the slider code in xaml:
<Slider x:Name="TheSlider" DockPanel.Dock="Left" Orientation="Horizontal" HorizontalAlignment="Center" HorizontalContentAlignment="Center" Minimum="-27" Maximum="27" Cursor="Hand" IsSnapToTickEnabled="True" Margin="322,392,329,87" ValueChanged="TheSlider_ValueChanged" Width="144" />
What is the problem here? Can you help me please?
UPDATE:
public override void OnApplyTemplate() { base.OnApplyTemplate(); System.Windows.Data.Binding b = new System.Windows.Data.Binding(); b.ElementName = "TheSlider"; b.Path = new PropertyPath("Value"); SetBinding(ElevationAngleProperty, b); } public int ElevationAngle { get { return _runtime.NuiCamera.ElevationAngle; } set { _runtime.NuiCamera.ElevationAngle = value; OnPropertyChanged("ElevationAngle"); } } public DependencyProperty ElevationAngleProperty { get; set; }
-
Samet about 12 yearsI'm getting errors from your code at SetBinding(ElevationAngleProperty, b); and OnPropertyChanged("ElevationAngle "); Can you check Update above in my code please? Where do I do wrong ?
-
Avani Vadera about 12 yearsHi Sameet, you seem to be using both the solution together. Instead of creating ElevationAngleProperty , simply bind the value of slider to ElevationAngle . It should work. Steps: 1.delete OnApplyTemplate funtion and ElevationAngleProperty 2. Bind Slider Value to ElevationAngle