Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need to bind to a dependency property in code behind but not in view model?

Tags:

c#

wpf

I'm writing a user control. Xaml & code behind. In order to bind to a property in the code behind the property needs to be a dependency property. Understood.

Why then can I bind to a poco which implements INotifyPropertyChanged in a view model which is set as the view's data context but not in the code behind?

xaml:

XAxis="{Binding ElementName=TimeSeriesChartControl, Path=XAxis}" 

Code behind:

public IAxis XAxis
{
    get { return (IAxis)GetValue(XAxisProperty); }
    set { SetValue(XAxisProperty, value); }
}

public static readonly DependencyProperty XAxisProperty =
    DependencyProperty.Register("XAxis", typeof(IAxis), typeof(TimeSeriesChart), new PropertyMetadata(default(IAxis)));

This property has to be a dependency property. If I was to implement a clr property here, the binding would fail.

Why can I implement a clr property in a view model class but not in the code behind?

like image 660
Hardgraf Avatar asked Dec 18 '22 11:12

Hardgraf


1 Answers

Because dependency properties support binding to both other dependency properties or to things that implement INotifyPropertyChanged.

A view model should try to stay platform agnostic and not know anything about the view, by using dependency properties in the view model you tie it to be WPF supported only and you are "leaking" information about the view back to the view model..

like image 160
Scott Chamberlain Avatar answered Dec 24 '22 01:12

Scott Chamberlain