I'm somewhat confused about WPF binding behavior. I've got a sliders value bound to a dependency property in code-behind (just for the example). The Minimum value of the slider is set in XAML. After the window is loaded, the value of the slider is set to the minimum, but the dependency property still has the default value of 0. However, the ValueChanged callback of the slider is being called, so I would actually expect the binding to be updated.
So I have the following window, one label shows the slider value, the other the property the value is bound to.
<Window x:Class="SliderBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525" x:Name="window">
<StackPanel DataContext="{Binding ElementName=window}">
<Slider Minimum="10" Maximum="100" x:Name="slider" Value="{Binding SliderValue, Mode=TwoWay}" ValueChanged="Slider_OnValueChanged"/>
<Label Content="{Binding Value, ElementName=slider}"></Label>
<Label Content="{Binding SliderValue}"></Label>
</StackPanel>
</Window>
and the code-behind which contains the dependency property and the event callback which simply prints a trace message when the slider value is changed.
using System;
using System.Diagnostics;
using System.Windows;
namespace SliderBinding
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
/* Sorry, wrong code
public double SliderValue
{
get; set;
}*/
public double SliderValue
{
get { return (double)GetValue(SliderValueProperty); }
set { SetValue(SliderValueProperty, value); }
}
public static readonly DependencyProperty SliderValueProperty =
DependencyProperty.Register("SliderValue", typeof(double), typeof(MainWindow), new PropertyMetadata(default(double)));
private void Slider_OnValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
Trace.TraceInformation("Slider value changed to {0}", e.NewValue);
}
}
}
As soon as I move the slider, both values are equal.
My question is, why is the dependency property not updated on startup, when the slider value is set to its minimum?
edits in italic.
INotifyPropertyChanged
correctly forSliderValue
. Your label that is bound to that value will not work correctly if you don't. – nvoigt