I’m trying to set up a property binding (WPF) in code. The code compiles fine, but the property I bind is never set. Below follows a minimal example:
The view-model:
public class FooViewModel: INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _value;
public string Value
{
get { return _value; }
set
{
_value = value;
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs("Value"));
}
}
}
The view:
public class FooView: Window
{
public string Value
{
get { return Title; }
set
{
// Breakpoint here never hits!
Title = value;
}
}
public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(FooView));
public FooView()
{
Binding valueBinding = new Binding("Value");
valueBinding.Mode = BindingMode.OneWay;
SetBinding(ValueProperty, valueBinding);
}
}
The “main()”:
FooView view = new FooView();
FooViewModel model = new FooViewModel();
view.DataContext = model;
view.Show();
model.Value = "ABC";
I expected the FooView.Value-setter to be invoked when model.Value is set. I’ve also tried explicitly setting the Binding.Source property to the model. How should the binding be set up?
The problem here is that the
Valueproperty is completely unrelated to theValuePropertydependency property.The CLR wrapper for a dependency property needs to call the DependencyObject’s GetValue and SetValue methods like below:
In order to get notified about property changes, you would have to register a PropertyChangedCallback with the PropertyMetadata:
Get more information in Custom Dependency Properties.