Including partial views when applying the Mode-View-ViewModel design pattern

Posted by Filip Ekberg on Stack Overflow See other posts from Stack Overflow or by Filip Ekberg
Published on 2011-03-08T07:34:31Z Indexed on 2011/03/08 8:10 UTC
Read the original article Hit count: 268

Filed under:
|
|
|

Consider that I have an application that just handles Messages and Users I want my Window to have a common Menu and an area where the current View is displayed.

I can only work with either Messages or Users so I cannot work simultaniously with both Views. Therefore I have the following Controls

  • MessageView.xaml
  • UserView.xaml

Just to make it a bit easier, both the Message Model and the User Model looks like this:

  • Name
  • Description

Now, I have the following three ViewModels:

  • MainWindowViewModel
  • UsersViewModel
  • MessagesViewModel

The UsersViewModel and the MessagesViewModel both just fetch an ObserverableCollection<T> of its regarding Model which is bound in the corresponding View like this:

<DataGrid ItemSource="{Binding ModelCollection}" />

The MainWindowViewModel hooks up two different Commands that have implemented ICommand that looks something like the following:

public class ShowMessagesCommand : ICommand
{
    private ViewModelBase ViewModel { get; set; } 
    public ShowMessagesCommand (ViewModelBase viewModel)
    {
        ViewModel = viewModel;
    }
    public void Execute(object parameter)
    {
        var viewModel = new ProductsViewModel();
        ViewModel.PartialViewModel = new MessageView { DataContext = viewModel };
    }

    public bool CanExecute(object parameter)
    {
        return true;
    }

    public event EventHandler CanExecuteChanged;
}

And there is another one a like it that will show Users. Now this introduced ViewModelBase which only holds the following:

    public UIElement PartialViewModel
    {
        get { return (UIElement)GetValue(PartialViewModelProperty); }
        set { SetValue(PartialViewModelProperty, value); }
    }

    public static readonly DependencyProperty PartialViewModelProperty =
        DependencyProperty.Register("PartialViewModel", typeof(UIElement), typeof(ViewModelBase), new UIPropertyMetadata(null));

This dependency property is used in the MainWindow.xaml to display the User Control dynamicly like this:

<UserControl Content="{Binding PartialViewModel}" />

There are also two buttons on this Window that fires the Commands:

  • ShowMessagesCommand
  • ShowUsersCommand

And when these are fired, the UserControl changes because PartialViewModel is a dependency property.

I want to know if this is bad practice? Should I not inject the User Control like this? Is there another "better" alternative that corresponds better with the design pattern? Or is this a nice way of including partial views?

© Stack Overflow or respective owner

Related posts about c#

Related posts about wpf