Navigation with MVVM

July 17, 2011

NOTE: I have re-written this article here to provide a better example, and some code samples.


When I first started out with MVVM, I was lost about how you should navigate between pages. I’m a firm believer in using ViewModels to do everything (unless it’s View-specific code), and that the UI is simply a user-friendly interface for your ViewModels. I did not want to create a button on a page that has any kind of code-behind to switch pages, and I didn’t like the idea of my navigation being spread out throughout all the ViewModels.

I finally came to realize the solution was simple: I needed a ViewModel for the Application itself, which contained the application state, such as the CurrentPage.

The ViewModel

Usually I name the ViewModel ShellViewModel or AppViewModel, but you can call it whatever you want. It is the startup page or window in the application, and is usually the only page/window object in my project.

It looks something like this:

    public class ShellViewModel : INotifyPropertyChanged
    {
        private ICommand _changeViewModelCommand;

        private object _currentViewModel;
        private List<object> _viewModels = new List<object>();

        public ShellViewModel()
        {
            ViewModels.Add(new HomeViewModel());
            CurrentViewModel = ViewModels[0];
        }

        private void ChangeViewModel(object viewModel)
        {
            if (!ViewModels.Contains(viewModel))
                ViewModels.Add(viewModel);

            CurrentViewModel = ViewModels.FirstOrDefault(vm => vm == viewModel);
        }
    }

I have omitted the public property implementation and the INotifyPropertyChanged interface methods for sake of readability. The public properties are your standard get/set properties that raise a PropertyChange notification, and the public ChangeViewModelCommand points to the ChangeViewModel method.

The View

I also need a ShellView for my ShellViewModel, so this is what it usually looks like:

<Grid Margin="20">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!-- Header -->
        <TextBlock Text="Application Name" FontWeight="Bold" FontSize="24" />

        <Line Grid.Row="1" Stroke="Black" Margin="0,5" StrokeThickness="1" Stretch="Fill" X2="1" />        <!-- Content -->
        <ContentControl Grid.Row="2" Content="{Binding CurrentViewModel}"/>
</Grid>

It contains a standard frame for the application, in this case the application name with a horizontal line under it, followed by the CurrentPage in a ContentControl. When a page is displayed in the ContentControl, WPF will lookup the appropriate DataTemplate to use to display that ViewModel (page).

Changing Pages

The ChangePage command can either be called directly through the XAML using something like this:

<Button Command="{Binding RelativeSource={RelativeSource
            AncestorType={x:Type Window}},
            Path=DataContext.ChangeViewModelCommand}
        CommandParameter="{Binding EditCustomerViewModel}"
        />

or you can use an Event system such as PRISM’s EventAggregator or MVVM Light’s Messenger, and the ViewModels would raise a ChangePage event. I prefer to use an Event system personally, but use whatever works for you.

For more on switching between Pages/Views, see this article


WPF Error: Specified element is already the logical child of another element. Disconnect it first.

July 17, 2011

The first time I saw this error, it completely threw me off. I had a ContentControl and in the style for it I was setting the Content to a wrapper for the ContentPresenter.

<Style x:Key="MyCustomContentControl" 
       TargetType="{x:Type ContentControl}">
    <Setter Property="Content">
        <Setter.Value>
            <local:MyCustomControl>
                <ContentPresenter />
            </local:MyCustomControl>
        </Setter.Value>
    </Setter>
</Style>

I would get this error whenever more than one ContentControl implemented this style.

I finally realized the error was telling me exactly what the issue was, I was just too blind to realize it. I was setting the Content, not the ContentTemplate. The specified element (MyCustomControl) was already the child of one ContentControl, so I could not add it as a child to another one.

I needed to switch my style to set the ContentTemplate, not the Content of my ContentControl. The way I currently had it written was like giving multiple people the same cookie to eat. It just didn’t work. Instead I needed to give them the cookie cutter so they could all make their own cookies, which is why I needed to set the Template instead of the Content.

<Style x:Key="MyCustomContentControl" 
       TargetType="{x:Type ContentControl}">
    <Setter Property="ContentTemplate">
        <Setter.Value>
            <local:MyCustomControl>
                <ContentPresenter />
            </local:MyCustomControl>
        </Setter.Value>
    </Setter>
</Style>

Definition of a DependencyProperty

July 17, 2011

I was recently asked what a DependencyProperty was and how it was different than a regular Property. The MSDN definition says the DependencyProperty class “represents a property that can be set through methods such as, styling, data binding, animation, and inheritance”, but that doesn’t really tell you what a DependencyProperty is, and why it is such an important part of WPF.

The real reason DependencyProperties are so special, is they are not meant to contain a value. Instead they are meant to contain a pointer, or address, of another value.

Instead of saying “This TextBox’s text is going to be Foo”, you end up saying “This TextBox’s text points to a string over here which currently contains Foo”.

The power in this is that it allows you to manipulate the source value without knowing about or altering the UI. If PropertyChange notification is setup, the UI will automatically display a new value without anyone ever touching it.

For example, suppose you had an online shopping application. The User’s Name is displayed in the welcome message, in the top right corner by the My Account link, and on the bottom in the Suggestions for <UserName> section. If the current user changes, you simply have to change a single property to the new value, and anywhere that displays the UserName will be updated automatically. You don’t need to remember which UI fields need to be updated or to change them all manually in the code.

So my definition of a DependencyProperty is a property that depends on another for its value.