WPF: Master detail for a class with data

This entry is part 48 of 54 in the series Learn WPF

In the previous example, we have used master detail view to show the running processes in a PC.

For this example, we work out a real world Person class and on each click to the ListBox on the left, the Age of the person will be shown on the right.

MainWindow.xaml
<Window x:Class="MasterDetail.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="200"/>
            <ColumnDefinition  />
        </Grid.ColumnDefinitions>
        <ListBox Name="lb" DisplayMemberPath="Name" />
        <Grid Grid.Column="1" TextBlock.FontSize="16" DataContext="{Binding SelectedItem, ElementName=lb}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
            </Grid.RowDefinitions>
            <TextBlock Margin="6" Text="{Binding Name, StringFormat='Name: \{0\}'}" />
            <TextBlock Grid.Row="1" Margin="6" Text="{Binding Age, StringFormat='Age: 0'}" />
        </Grid>
        <GridSplitter Background="Blue" Width="2" HorizontalAlignment="Right" VerticalAlignment="Stretch" />
    </Grid>
</Window>

MainWindow.xaml.cs
using System.Collections.Generic;
using System.Windows;

namespace MasterDetail
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        class Person
        {
            public string Name { get; set; }
            public int Age { get; set; }
        }

        List<Person> people = new List<Person> {
              new Person { Name = "Michelle", Age = 10 },
              new Person { Name = "Emily", Age = 45 },
              new Person { Name = "John", Age = 35 },
              new Person { Name = "Lisa", Age = 12 },
              new Person { Name = "Maggie", Age = 1 }
            };

        public MainWindow()
        {
            InitializeComponent();
            lb.ItemsSource = people;
        }
    }
}

As the left column master view is a ListBox, we build a Person class and create a few instances of the class and put the instances into a list.

masterdetaillist

 

Series Navigation<< WPF: Master-detail view
WPF: Implementing dependency properties >>