Search code examples
wpfuser-controlsmvvmdependency-properties

WPF User Control hell with MVVM and Dependency Properties


This is what I'm trying to do:

  • I'm writing a UserControl that I want to be consumed by other developers.
  • I want end users to be able to use my control using Dependency Properties.

    <lib:ControlView ControlsText={Binding Path=UsersOwnViewModelText} />
    
  • I'm using the MVVM pattern.

  • I'm binding my ViewModels to their View's using <DataTemplates>

    <DataTemplate DataType="{x:Type local:ControlViewModel}">  
        <local:ControlView />  
    </DataTemplate>
    

So I have two questions:

  1. Am I right in thinking that if a UserControl is being consumed in XAML then the UserControl must set the ViewModel as its DataContext when the control's Loaded event fires instead of using the <DataTemplate> method?

  2. How do I allow users to data bind to my control's dependency properties while still being data bound to my ViewModel?


Solution

  • First off, I don't think MVVM is a good choice if you are developing a UserControl that will be consumed by others. A lookless control is what you really should be developing. Jeremiah Morrill has a blog post about this subject.

    With that said, you can set the datacontext with XAML if you have a default public constructor.

    Inside ControlView.xaml put:

    <UserControl.DataContext>
        <local:ControlViewModel />
    </UserControl.DataContext>