9
votes

Hi I am building a wpf application in which a screen will be comprising of different user controls for performing various application.

I wanted to know the right process for doing this in MVVM? Should each user control have its own view model, or should they still bind to the main View model properties?

Please suggest a good approach. Thanks,

2

2 Answers

5
votes

When I use an UserControl I pass the data through DependencyProperties. My UserControls doesn't have ViewModels. UserControls only handle the passed data a very special way.

But if I have View that contains some Sub-Views I prefere to have for each Sub-View a own model. These model I'll bind through a property of the ViewModel of the MainView.

Some example:

UserControl1, Code behind:

public partial class UserControl1 : UserControl
{
    public MyClass MyProperty
    {
        get { return (MyClass)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }

    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(MyClass), typeof(UserControl1), new UIPropertyMetadata(null));


    public UserControl1()
    {
        InitializeComponent();
    }
}

 public class MyClass
{
    public int MyProperty { get; set; }
}

And the usage in the view, XAML:

<Window x:Class="Sandbox.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:Sandbox="clr-namespace:Sandbox">
  <Grid>
    <Sandbox:UserControl1 MyProperty="{Binding MyOtherPropertyOfTypeMyClassInMyViewModel, Mode=TwoWay}" />
  </Grid>

Hope this helps

1
votes

Good question - but I don't think there's one straight-forward answer.

It depends a lot on the shape of your data. If the different User Controls are different views on the same data then there's no reason why they can't share the same ViewModel...that's one of the driving forces of MVVM - you can give the same ViewModel to different Views to show the same data in different ways.

But then again, if your ViewModel starts to really bloat and there's not much overlap then break it up into smaller ViewModels. Maybe then your main ViewModel just becomes more of a ViewModel manager with a collection of ViewModels to hand out to the various User Controls as appropriate?