Reputation: 21
I made a UserControl with the MVVM pattern, where the UserControl's "intelligence" is in its viewModel.
I want to user that UserControl in different views (xaml) so the developer of that view doesn't have to mind about how it is done.
I added some dependencyProperties in my UserControl so the end-programmer could give the control some context informations.
But I have some binding issues.
In the client.xaml:
<Grid>
<MyUserControl MyDependencyProperty0={Binding ClientViewModelProperty0}/>
</Grid>
and in myusercontrol.xaml
<Grid>
<TextBlock Text={Binding TextToDisplay}/>
</Grid>
where TextToDisplay is a property of MyUserControlViewModel. I only need the ClientViewModelProperty0 to be set once, I do not need the clientViewModel to be set as the DataContext of MyUserControl since it has its own dataContext(its view-model)
I assume the solution would be a different Binding Expression syntax (relative source? self?) but I cannot see which one...
Upvotes: 2
Views: 603
Reputation: 25623
Reusable controls tend to follow a somewhat different design than full-blown application views. Specifically, they don't follow MVVM in quite the same way.
Remember that in WPF, controls are "lookless": their visual appearance is governed by templates. The underlying class is the "model" for the control. Like @Will mentioned in his comment, a TextBox
does not have a TextBoxViewModel
; the TextBox
instance is the "view model". The "view" is the template that gets applied. While a UserControl
is a bit different from a templated control (its content is self-contained, so it's effectively both the "view" and the "view model"), the same basic rules apply:
When you create your own reusable controls, put your properties and behavior in the control class itself. That way, when you plug it in to a view, you can set the parameters however you like, e.g., by binding them against the parent view model. A reusable control should never rely on some external/ambient view model being present.
Upvotes: 2