mark_h mark_h - 28 days ago 10
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); }
set
{
SetValue(ViewModelProperty, value);
}
}

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


This is the constructor for the "MyCustomControl";

public MyCustomControl()
{
InitializeComponent();
}


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

Answer

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

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