Telerik blogs

After our brief intermission (and the craziness of Q1 2010 release week), we're back on track here and today we get to dive into how we are going to navigate through our applications as well as how to set up our modules.  That way, as I start adding the functionality- adding Jobs and Applicants, Interview Scheduling, and finally a handy Dashboard- you'll see how everything is communicating back and forth.  This is all leading up to an eventual webinar, in which I'll dive into this process and give a honest look at the current story for MVVM vs. Code-Behind applications.  (For a look at the future with SL4 and a little thing called MEF, check out what Ross is doing over at his blog!)

Preamble...

Before getting into really talking about this app, I've done a little bit of work ahead of time to create a ton of files that I'll need.  Since the webinar is going to cover the Dashboard, it's not here, but otherwise this is a look at what the project layout looks like (and remember, this is both projects since they share the .Web):

Solution

So as you can see, from an architecture perspective, the code-behind app is much smaller and more streamlined- aka a better fit for the one man shop that is me.  Each module in the MVVM app has the same setup, which is the Module class and corresponding Views and ViewModels.  Since the code-behind app doesn't need a go-between project like Infrastructure, each MVVM module is instead replaced by a single Silverlight UserControl which will contain all the logic for each respective bit of functionality.

My Very First Module

Navigation is going to be key to my application, so I figured the first thing I would setup is my MenuModule.  First step here is creating a Silverlight Class Library named MenuModule, creating the View and ViewModel folders, and adding the MenuModule.cs class to handle module loading.  The most important thing here is that my MenuModule inherits from IModule, which runs an Initialize on each module as it is created that, in my case, adds the views to the correct regions.  Here's the MenuModule.cs code:

public class MenuModule : IModule
{
    private readonly IRegionManager regionManager;
    private readonly IUnityContainer container;
    public MenuModule(IUnityContainer container, IRegionManager regionmanager)
    {
        this.container = container;
        this.regionManager = regionmanager;
    }
    public void Initialize()
    {
        var addMenuView = container.Resolve<MenuView>();
        regionManager.Regions["MenuRegion"].Add(addMenuView);
    }
}

Pretty straightforward here... We inject a container and region manager from Prism/Unity, then upon initialization we grab the view (out of our Views folder) and add it to the region it needs to live in.  Simple, right?  When the MenuView is created, the only thing in the code-behind is a reference to the set the MenuViewModel as the DataContext.  I'd like to achieve MVVM nirvana and have zero code-behind by placing the viewmodel in the XAML, but for the reasons listed further below I can't.

Navigation - MVVM

Since navigation isn't the biggest concern in putting this whole thing together, I'm using the Button control to handle different options for loading up views/modules.  There is another reason for this- out of the box, Prism has command support for buttons, which is one less custom command I had to work up for the functionality I would need.  This comes from the Microsoft.Practices.Composite.Presentation assembly and looks as follows when put in code:

<Button x:Name="xGoToJobs"
        Style="{StaticResource menuStyle}"
        Content="Jobs"
        cal:Click.Command="{Binding GoModule}"
        cal:Click.CommandParameter="JobPostingsView" />

For quick reference, 'menuStyle' is just taking care of margins and spacing, otherwise it looks, feels, and functions like everyone's favorite Button.  What MVVM's this up is that the Click.Command is tying to a DelegateCommand (also coming from Prism) on the backend.  This setup allows you to tie user interaction to a command you setup in your viewmodel, which replaces the standard event-based setup you'd see in the code-behind app.  Due to databinding magic, it all just works.  When we get looking at the DelegateCommand in code, it ends up like this:

public class MenuViewModel : ViewModelBase
{
    private readonly IRegionManager regionManager;
    public DelegateCommand<object> GoModule { get; set; }
    public MenuViewModel(IRegionManager regionmanager)
    {
        this.regionManager = regionmanager;
        this.GoModule = new DelegateCommand<object>(this.goToView);
    }
    public void goToView(object obj)
    {
        MakeMeActive(this.regionManager, "MainRegion", obj.ToString());
    }
}

Another for reference, ViewModelBase takes care of iNotifyPropertyChanged and MakeMeActive, which switches views in the MainRegion based on the parameters.  So our public DelegateCommand GoModule ties to our command on the view, that in turn calls goToView, and the parameter on the button is the name of the view (which we pass with obj.ToString()) to activate.  And how do the views get the names I can pass as a string?  When I called regionManager.Regions[regionname].Add(view), there is an overload that allows for .Add(view, "viewname"), with viewname being what I use to activate views.  You'll see that in action next installment, just wanted to clarify how that works.

With this setup, I create two more buttons in my MenuView and the MenuModule is good to go.  Last step is to make sure my MenuModule loads in my Bootstrapper:

protected override IModuleCatalog GetModuleCatalog()
{
    ModuleCatalog catalog = new ModuleCatalog();
    // add modules here
    catalog.AddModule(typeof(MenuModule.MenuModule));
    return catalog;
}

Clean, simple, MVVM-delicious. 

Navigation - Code-Behind

Keeping with the history of significantly shorter code-behind sections of this series, Navigation will be no different. I promise.

As I explained in a prior post, due to the one-project setup I don't have to worry about the same concerns so my menu is part of MainPage.xaml.  So I can cheese-it a bit, though, since I've already got three buttons all set I'm just copying that code and adding three click-events instead of the command/commandparameter setup:

<!-- Menu Region -->
<StackPanel Grid.Row="1"
            Orientation="Vertical">
    <Button x:Name="xJobsButton"
            Content="Jobs"
            Style="{StaticResource menuStyleCB}"
            Click="xJobsButton_Click" />
    <Button x:Name="xApplicantsButton"
            Content="Applicants"
            Style="{StaticResource menuStyleCB}"
            Click="xApplicantsButton_Click" />
    <Button x:Name="xSchedulingModule"
            Content="Scheduling"
            Style="{StaticResource menuStyleCB}"
            Click="xSchedulingModule_Click" />
</StackPanel>

Simple, easy to use events, and no extra assemblies required!  Since the code for loading each view will be similar, we'll focus on JobsView for now. The code-behind with this setup looks something like...

private JobsView _jobsView;
public MainPage()
{
    InitializeComponent();
}
private void xJobsButton_Click(object sender, RoutedEventArgs e)
{
    if (MainRegion.Content.GetType() != typeof(JobsView))
    {
        if (_jobsView == null)
            _jobsView = new JobsView();
        MainRegion.Content = _jobsView;
    }
}

What am I doing here?  First, for each 'view' I create a private reference which MainPage will hold on to.  This allows for a little bit of state-maintenance when switching views.  When a button is clicked, first we make sure the 'view' type isn't active (why load it again if it is already at center stage?), then we check if the view has been created and create if necessary, then load it up.  Three steps to switching views and is easy as pie. 

Part 4 Results

The end result of all this is that I now have a menu module (MVVM) and a menu section (code-behind) that load their respective views.  Since I'm using the same exact XAML (except with commands/events depending on the project), the end result for both is again exactly the same and I'll show a slightly larger image to show it off:

RecruitMainView

Next time, we add the Jobs Module and wire up RadGridView and a separate edit page to handle adding and editing new jobs.  That's when things get fun.  And somewhere down the line, I'll make the menu look slicker. :)


About the Author

Evan Hutnick

works as a Developer Evangelist for Telerik specializing in Silverlight and WPF in addition to being a Microsoft MVP for Silverlight. After years as a development enthusiast in .Net technologies, he has been able to excel in XAML development helping to provide samples and expertise in these cutting edge technologies. You can find him on Twitter @EvanHutnick.

Comments

Comments are disabled in preview mode.