mark_h mark_h - 1 year ago 116
C# Question

Can I set my user control datacontext in xaml via a dependency property bound to a property on the parent control in wpf?

I have a user control with a dependency property called ViewModel. I want the value that this property is set to to be the data context for this control.

Here is an example of its usage;

<uc:MyCustomControl ViewModel="{Binding CustomControlViewModel}"/>

Here is the code-behind for the ViewModel dependency property for "MyCustomControl"

public static readonly DependencyProperty ViewModelProperty = DependencyProperty.Register(
"ViewModel", typeof(CustomControlViewModel), typeof(MyCustomControl), new PropertyMetadata(default(CustomControlViewModel), PropertyChangedCallback));

public CustomControlViewModel ViewModel
get { return (CustomControlViewModel)GetValue(ViewModelProperty); }
SetValue(ViewModelProperty, value);

private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
var control = (MyCustomControl) dependencyObject;
if (control == null)
control.DataContext = (CustomControlViewModel) dependencyPropertyChangedEventArgs.NewValue;

This is the constructor for the "MyCustomControl";

public MyCustomControl()

This doesn't seem to work, what might I be doing wrong?

Answer Source

DataContext itself is a DependencyProperty. You can directly assign it with your viewmodel like this.

<uc:MyCustomControl DataContext="{Binding CustomControlViewModel}"/>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download