Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get and bind the value of Slider in C# WPF?

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; }
like image 895
Samet Avatar asked Oct 25 '25 01:10

Samet


1 Answers

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.

like image 97
Goot Avatar answered Oct 26 '25 14:10

Goot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!