-
- antsonthetree
- Posts: 44
- Joined:
Binding a Slider
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.
In my code behind (currently c# for testing) I have a property (double SliderVal) that I set to 50 in the OnInitialized function:
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
Code: Select all
<Slider Minimum="0" Maximum="100" x:Name="TestSlider" Value="{Binding SliderVal, Mode=TwoWay}" ValueChanged="Slider_OnValueChanged"/>
Code: Select all
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);
}
}
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
- Posts: 44
- Joined:
Re: Binding a Slider
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
Jake
-
-
sfernandez
Site Admin
- Posts: 3364
- Joined:
Re: Binding a Slider
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
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 20 guests