This is what I’m trying to do:
- I’m writing a
UserControlthat 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:
-
Am I right in thinking that if a UserControl is being consumed in XAML then the UserControl must set the ViewModel as its
DataContextwhen the control’sLoadedevent fires instead of using the<DataTemplate>method? -
How do I allow users to data bind to my control’s dependency properties while still being data bound to my ViewModel?
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: