antsonthetree
Topic Author
Posts: 44
Joined: 09 Jan 2018, 15:56

Binding a Slider

09 Feb 2018, 00:49

I am trying to bind the slider to a property in my view model - for a volume control. So far I can get the ValueChanged event to fire on the VM, but I cannot figure out how to set the initial slider value from the VM. This is how my slider is set in xaml.
<Slider Minimum="0" Maximum="100" x:Name="TestSlider" Value="{Binding SliderVal, Mode=TwoWay}" ValueChanged="Slider_OnValueChanged"/>
In my code behind (currently c# for testing) I have a property (double SliderVal) that I set to 50 in the OnInitialized function:
  public partial class M2_SettingsAudio : UserControl
    {
        public M2_SettingsAudio()
        {
            this.Initialized += OnInitialized;
            this.InitializeComponent();
        }

        private void OnInitialized(object sender, EventArgs args)
        {
            this.DataContext = new AudioViewModel();
            Console.WriteLine("Audio Initialized");
            SliderVal = 50;
        }
        public double SliderVal = 50;

        public void Slider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            Console.WriteLine("Slider value changed to {0}", e.NewValue);
            Console.WriteLine("SliderVal is {0}", SliderVal);
        }
    }
When I run in Xaml Viewer the slider is always initialized at 0, not 50. I want to be able to set it from the code.
I searched the samples but none of them do a two way bind of a slider to a VM (unless I missed one).
Would love to know what I'm doing wrong - Many thanks!

Jake
 
antsonthetree
Topic Author
Posts: 44
Joined: 09 Jan 2018, 15:56

Re: Binding a Slider

09 Feb 2018, 03:21

UPDATE: I got this working with my viewmodel. I was way off base. I'm new to xaml. The trick was deriving the VM from NotifyPropertyChandedBase, and then calling OnPropertyChanged in the setter. Everything is peachy now thanks!

Jake
 
User avatar
sfernandez
Site Admin
Posts: 1912
Joined: 22 Dec 2011, 19:20

Re: Binding a Slider

09 Feb 2018, 21:02

That's right, your VM needs to notify when property changes in order to update the UI.
If you need more info on DataBinding you can read the corresponding tutorial: https://www.noesisengine.com/docs/Gui.C ... orial.html

Who is online

Users browsing this forum: No registered users and 0 guests