Reputation: 385
I have a UserControl MyView, which has an inner UserControl SubView.
The view models of the 2 UserControls have the same hierarchical structure as the views, i,e, MyViewModel has SubViewModel inside as shown in the code below.
public class MyViewModel
{
private readonly SubViewModel _subViewModel = new SubViewModel();
public SubViewModel SubViewModel { get { return _subViewModel; } }
private void HandleSubViewModel()
{
// Do what is necessary to handle SubViewModel
}
}
My question is about how to bind SubViewModel to SubView.
Now I define SubViewModel in the code-behind of SubView and bind it to the SubViewModel property of MyViewModel class.
public partial class SubView : UserControl
{
public static readonly DependencyProperty SubViewModelProperty = DependencyProperty.Register(
"SubViewModel", typeof (SubViewModel), typeof (SubView), new PropertyMetadata(default(SubViewModel)));
public SubViewModel SubViewModel
{
get { return (SubViewModel) GetValue(SubViewModelProperty); }
set { SetValue(SubViewModelProperty, value); }
}
}
<UserControl x:Class="MyProject.View.MyView"
xmlns:parts="clr-namespace:MyProject.View.Parts">
<Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}, Path=MyViewModel}">
<parts:SubView SubViewModel="{Binding SubViewModel}"/>
</Grid>
</UserControl>
Is it a bad practice to bind an inner view model in this way?
If so, how can I bind it in a better way?
Upvotes: 0
Views: 304
Reputation: 2246
You can do like this: View models:
public class MyViewModel
{
private readonly SubViewModel _subViewModel;
public SubViewModel SubViewModel
{
get { return _subViewModel; }
}
public MyViewModel()
{
_subViewModel = new SubViewModel();
_subViewModel.Text1 = "blabla";
}
}
public class SubViewModel : DependencyObject
{
public string Text1
{
get { return (string)GetValue(Text1Property); }
set { SetValue(Text1Property, value); }
}
public static readonly DependencyProperty Text1Property =
DependencyProperty.Register("Text1", typeof(string), typeof(SubViewModel));
}
SubUserControl:
<UserControl x:Class="WpfApplication1.SubUserControl"
xmlns= ... >
<Grid Height="200" Width="300" Background="Aqua">
<TextBlock Text="{Binding SubViewModel.Text1}" />
</Grid>
Upvotes: 0
Reputation: 4487
One reason why it could be bad is that if a property inside the SubViewModel
changes, there is no way that the MyViewModel
would know about that. So for e.g. if there are any validations that you need to carry out and handle at the MyViewModel
level, you would not be able to do that.
To work around that, when a property changes; you would have to raise an event in the SubViewModel
and make the MyViewModel
subscribe to it and react appropriately after receiving it.
Apart from that I see no drawbacks as such. But do read these links for further info: MVVM and nested view models
MVVM: How to handle interaction between nested ViewModels?
Upvotes: 3