Page 1 of 1

Binding a Slider

Posted: 09 Feb 2018, 00:49
by antsonthetree
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

Re: Binding a Slider

Posted: 09 Feb 2018, 03:21
by antsonthetree
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

Re: Binding a Slider

Posted: 09 Feb 2018, 21:02
by sfernandez
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