Keep in mind that I have an application that simply processes Messages and Users . I want my window to have a common Menu and the area where the current View displayed.
I can only work with messages or users, so I can not work simultaneously with both views. Therefore, I have the following controls
- MessageView.xaml
- Userview.xaml
Just to make it a little easier, both Message Model and User Model look like this:
Now I have the following three types of Models:
- MainWindowViewModel
- UsersViewModel
- MessagesViewModel
UsersViewModel and MessagesViewModel both simply retrieve the ObserverableCollection<T> it relative to the Model , which is linked in the corresponding View as follows:
<DataGrid ItemSource="{Binding ModelCollection}" />
MainWindowViewModel connects two different Commands that have implemented ICommand , which looks something like this:
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 that will show users. Now it has introduced ViewModelBase , which only has 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 MainWindow.xaml to dynamically display User Control as follows:
<UserControl Content="{Binding PartialViewModel}" />
There are two buttons in this Window that launch commands:
- ShowMessagesCommand
- ShowUsersCommand
And when they start, UserControl changes because PartialViewModel is a dependency property.
I want to know if this is bad practice? Should I not introduce a user control this way? Is there another “better” alternative that better matches the design pattern? Or is this a good way to include partial views?