WPF: DisplayMemberPath

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

Using DisplayMemberPath, we can display selected property in a class.  Since ListBox is like a single column list, we will display only one property in the class.

Running the code below will only display the names.

MainWindow.xaml
<Window x:Class="ListBoxBinding.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>
        <ListBox x:Name="lb" DisplayMemberPath="Name">
        </ListBox>
    </Grid>
</Window>

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

namespace ListBoxBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        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;
        }
    }
}

Person.cs
namespace ListBoxBinding
{
    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

displaymemberpath

 

 

 

 

 

Series Navigation<< WPF: Binding to a collection
WPF: Add new data with notification >>

Leave a comment

Leave a Reply