5

I have decided to use the MVVM Light library to help design a UI. After tons of research and trial and error, I have yet to find the answers I am looking for. I've googled and read each StackOverflow question I can find, however, my problem seems to be unique on SO.

I wish to design a UI with a single window and populate it with different Views/UserControls. I do NOT want a shared navigation bar among the UserControls nor do I want multiple windows to pop-up. Each View/UserControl should bind to its own ViewModel, while the MainWindow will bind to a MainViewModel.

Example scenario - MainWindow with 3 UserControls

1. MainWindow populates with first UserControl which has a listbox and 3 buttons, the first button is enabled.
2. User clicks the first button.
3. MainWindow populates with second UserControl.

Or, additionally

 2. User selects choice from a listbox, button two and three become available.
 3. User clicks second/third button.
 4. MainWindow populates with second/third UserControl.

Etc, etc.

Perhaps my approach isn't realistic, but I feel this has to be possible. I do not understand how to make all of these pieces work conceptually. There is no way my desires are unique. If you feel this is duplicate question, please redirect. Cheers.


To make things easier to understand, I've included some classes below. First, my App.xaml.

<Application x:Class="Bobcat_BETA.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:views="clr-namespace:Bobcat_BETA.UserControls"
             xmlns:vm="clr-namespace:Bobcat_BETA.ViewModels"
             StartupUri="MainWindow.xaml"
             mc:Ignorable="d">
    <Application.Resources>
        <vm:ViewModelLocator x:Key="Locator" d:IsDataSource="True" />

        <DataTemplate DataType="{x:Type vm:SavedScenariosViewModel}">
            <views:SavedScenariosUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:ScenarioEditorViewModel}">
            <views:ScenarioEditorUserControl />
        </DataTemplate>
        <DataTemplate DataType="{x:Type vm:SimulatorViewModel}">
            <views:SimulatorUserControl />
        </DataTemplate>

    </Application.Resources>
</Application>

MainWindow.xaml

<Window x:Class="Bobcat_BETA.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Bobcat - Version:0.00"
    DataContext="{Binding Main, Source={StaticResource Locator}}">
<Grid>
    <ContentControl Content="{Binding CurrentView}"/>
</Grid>

ViewModelLocator.cs

namespace Bobcat_BETA.ViewModels
{

    public class ViewModelLocator
    {

        private static MainViewModel _main;

        public ViewModelLocator()
        {
            _main = new MainViewModel();
        }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
            "CA1822:MarkMembersAsStatic",
            Justification = "This non-static member is needed for data binding purposes.")]
        public MainViewModel Main
        {
            get
            {
                return _main;
            }
        }
    }
}

MainViewModel.cs

namespace Bobcat_BETA.ViewModels
{
    public class MainViewModel : ViewModelBase
    {
        private ViewModelBase _currentViewModel;

        readonly static SavedScenariosViewModel _savedScenarioViewModel = new SavedScenariosViewModel();
        readonly static ScenarioEditorViewModel _scenarioEditorViewModel = new ScenarioEditorViewModel();
        readonly static SimulatorViewModel _simulatorViewModel = new SimulatorViewModel();

        public ViewModelBase CurrentViewModel
        {
            get
            {
                return _currentViewModel;
            }
            set
            {
                if (_currentViewModel == value)
                    return;
                _currentViewModel = value;
                RaisePropertyChanged("CurrentViewModel");
            }
        }

        public MainViewModel()
        {
            CurrentViewModel = MainViewModel._savedScenarioViewModel;
            SavedScenarioViewCommand = new RelayCommand(() => ExecuteSavedScenarioViewCommand());
            ScenarioEditorViewCommand = new RelayCommand(() => ExecuteScenarioEidtorViewCommand());
            SimulatorViewCommand = new RelayCommand(() => ExecuteSimulatorViewCommand());
        }

        public ICommand SavedScenarioViewCommand { get; private set; }
        public ICommand ScenarioEditorViewCommand { get; private set; }
        public ICommand SimulatorViewCommand { get; private set; }

        private void ExecuteSavedScenarioViewCommand()
        {
            CurrentViewModel = MainViewModel._savedScenarioViewModel;
        }

        private void ExecuteScenarioEidtorViewCommand()
        {
            CurrentViewModel = MainViewModel._scenarioEditorViewModel;
        }

        private void ExecuteSimulatorViewCommand()
        {
            CurrentViewModel = MainViewModel._simulatorViewModel;
        }
    }
}

SavedScenariosViewModel.cs

namespace Bobcat_BETA.ViewModels
{
    public class SavedScenariosViewModel : ViewModelBase
    {

        public SavedScenariosViewModel()
        {
        }

        ObservableCollection<ScenarioModel> _scenarioModels = new ObservableCollection<ScenarioModel>()
        {
            new ScenarioModel() {Name = "Scenario 0", ID = 000, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 1", ID = 001, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 2", ID = 002, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 3", ID = 003, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 4", ID = 004, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 5", ID = 005, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 6", ID = 006, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 7", ID = 007, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 8", ID = 008, Desc = "This will describe the Scenario Model."},
            new ScenarioModel() {Name = "Scenario 9", ID = 009, Desc = "This will describe the Scenario Model."}
        };
        public ObservableCollection<ScenarioModel> ScenarioModels
        {
            get { return _scenarioModels; }
        }

    }
}

SavedScenariosUserControl.xaml

<UserControl x:Class="Bobcat_BETA.UserControls.SavedScenariosUserControl"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:vm="clr-namespace:Bobcat_BETA.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">

    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="/Dictionaries/MasterDictionary.xaml" />
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>

    <UserControl.Style>
        <DynamicResource ResourceKey="GeneralUserControl"/>
    </UserControl.Style>

    <Grid>
        <Label Content="Saved Scenario Selection" 
                Style="{StaticResource GeneralLabel}" HorizontalAlignment="Left" Margin="26,30,0,0" VerticalAlignment="Top" Height="62" Width="345"/>
        <Label Content="Chose Flight Model:" 
                Style="{StaticResource GeneralLabel2}"
                HorizontalAlignment="Left" Margin="27,111,0,0" VerticalAlignment="Top" Height="43" Width="345"/>
        <ListBox Style="{StaticResource GeneralListBox}"
                HorizontalAlignment="Left" Height="509" Margin="27,154,0,0" VerticalAlignment="Top" Width="345"
                ItemsSource="{Binding ScenarioModels}"/>

        <Button Content="New" 
                Style="{StaticResource TransitionButton}"
                HorizontalAlignment="Left" Margin="948,601,0,0" VerticalAlignment="Top" MinHeight="62" MinWidth="150" IsEnabled="True"
                Command="{Binding ScenarioEditorViewCommand}"/>

        <Button Content="Edit"
                Style="{StaticResource TransitionButton}"
                HorizontalAlignment="Left" Margin="401,519,0,0" VerticalAlignment="Top" MinHeight="62" MinWidth="150"
                Command="{Binding SaveScenariosViewCommand}"/>
        <Button Content="Load"
                Style="{StaticResource TransitionButton}"
                HorizontalAlignment="Left" Margin="401,601,0,0" VerticalAlignment="Top" MinHeight="62" MinWidth="150"
                Command="{Binding SimulatorViewCommand}"/>

    </Grid>
</UserControl>

If anything is unclear, I can add the Model classes as well, but I assume you can make inferences from what is going on. Thanks.

piofusco
  • 229
  • 2
  • 14

2 Answers2

3

So your approach is very plausible. There are certain intricacies you'll have to use in order to get that functionality. I had to use a "MainViewModel" which contained all the view models. These view models behave such that when the data context switched to a different view model, the corresponding user control would change to the appropriate view. A good example which I followed was answered by Sheridan here. Hook into your app.xaml with the appropriate data templates and data context switches will be handled like magic :D

Where I diverged from Sheridan's example (because I didn't want to create a separate relay command class/object), I actually used mvvm light (galasoft) to send messages from my viewmodels to message back to the "MainViewModel" to switch its data context. A good example of using MVVM light messaging can be found here. Send the message from the "child" View Model and register it in the "MainViewModel."

Good luck!

Community
  • 1
  • 1
Stunna
  • 413
  • 6
  • 16
  • I actually have my App.xaml laid out exactly like the first example you mentioned. Instead of deriving my ViewModels from BaseViewModel, I derive from ViewModelBase from MVVM Light. I am a bit lost on Messenger though. Tomorrow I'll post all my classes for all to gander at. – piofusco Oct 08 '14 at 21:51
  • Okay! You lost me a bit on how you derive your ViewModelBase from MVVM Light. But yeah post your code and I'll take a look. – Stunna Oct 08 '14 at 22:04
  • So I haven't been able to really dig into your code into too much detail, but I never got my ViewModelLocator to work. So I just axed that part of my code. Instead, I set the datacontext of the main window to the mainviewmodel that you have setup. Then the binding in your main window can be to your "currentviewmodel". Now what you're missing is the messaging system. I used NuGet to grab the galasoft package for MVVM light messaging. Once you have that installed, follow that example of the MVVM light messaging pattern. – Stunna Oct 10 '14 at 18:52
  • FYI: the pattern is to create a generic "message" class with your data, message, etc. Encapsulate the message you want to send in that class. Then, create a function of parsing that message, and then switch to the appropriate viewmodel by setting the datacontext. Then, still in your mainviewmodel, register to recieve messages using the method you just created. After setting that up, you can "send" the message in your SavedScenariosViewModel by hooking that send message into a button action (or whatever you're trying to achieve to act as the trigger to switch views). – Stunna Oct 10 '14 at 18:56
  • 1
    This post inspired a break through. Thanks Stunna, you are a stunna. I have enough to continue! – piofusco Oct 11 '14 at 01:48
  • @Stunna Do either of you know where there is a functional example of this? I've been trying to get this working for a few weeks off and on now. I keep getting stuck on the first link where the button command binds to the parents property. I get "cannot resolve DatContext" and have been pretty much stuck. I feel a functional example would be super helpful and would build it myself but I can't get it working >.>. Any help or pointers would be super appreciated! – Frito Sep 11 '15 at 01:34
  • Hey Frito, was out of country. Post some code if you could! But it sounds like maybe your view might be missing the "DataContext = (whichever VM you're setting for your data context)" in your constructor for the view? – Stunna Sep 24 '15 at 20:39
1

Can't you use an Interface for exemple IChildLayout ? Each ViewModel inherit of this interface...

public interface IChildLayout:INotifyPropertyChanged
{
    public MainWindows_ViewModel Parent;
}

In your MainWindows ViewModel you can have something like this...

A property IChildLayout, which changes when you click on your buttons...

public class MainWindows_ViewModel:INotifyPropertyChanged
{
    public MainWindows_ViewModel()
    {
        //Here i set the default ViewModel
        this.Child=new First_ViewModel(){Parent=this};
    }

    private IChildLayout _child;
    public IChildLayout Child
    {
        get
        {
            return _child;
        }
        set
        {
            _child=value;
            _child.Parent=this;
            NotifyPropertyChanged("Child");
        }
    }
    #region INotifyPropertyChangedMembers...
}

For each layout you can retrieve the parent window ViewModel (it is important to switch the layout by editing the "Child" property from it's own ViewModel...)

You put a UserControl inside of your mainwindows (in the xaml), the content is Binded to your Child property then it will be refresh each time you change your Child property.

<Windows>
    <Windows.DataContext>
        <local:MainWindows_ViewModel/>
    </Windows.DataContext>
    <UserControl Content={Binding Child}>
        <UserControl.Resources>
            <DataTemplate DataType="{x:Type ViewModels:First_ViewModel}">
                    <Controls:First_View DataContext="{Binding}"/>
            </DataTemplate>
            <DataTemplate DataType="{x:Type ViewModels:Second_ViewModel}">
                    <Controls:Second_View DataContext="{Binding}" />
            </DataTemplate>
         </UserControl.Resources>
    </UserControl>
</Windows>

In this case, your First_ViewModel can be : (In this sample, I use prism DelegateCommand to bind button actions...

public class First_ViewModel:IChildLayout
{
public MainWindows_ViewModel Parent {get;set;}

public ICommand cmdBtn1click{get;set;}
private Pass_to_second_ViewModel()
{
    //Here i change the Parent Child Property, it will switch to Second_View.xaml...
    this.Parent.Child=new Second_ViewModel();
}

public First_ViewModel()
{
    // Here i connect the button to the command with Prism...
    this.cmdBtn1click=new DelegateCommand(()=>Pass_to_second_ViewModel());

}

#region INotifyPropertyChangedMembers...

}

I hope this will help you, i did this sort of thing to manage different Tab in a WPF application.

FrsECM
  • 245
  • 2
  • 16
  • This looks logically sound, so I am going to try my best to get this working. Any additional code examples would be welcomed. Thanks. – piofusco Oct 08 '14 at 21:19