Visual Studio / WPF > ListBox | DataGrid > DisplayMemberPathの使用例


動作環境
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2

ListBoxやDataGridで使うDisplayMemberPathの使い方の整理。

参考: http://gushwell.ldblog.jp/archives/52305448.html
参考: http://iyemon018.hatenablog.com/entry/2015/10/17/203939

DisplayMemberPath
表示するデータの名称
ItemsSource にバインドしたコレクション単体の型のプロパティ名でなければならない。

実装してみた。

MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
//
using System.Collections.ObjectModel;

namespace _170605_t1315_DisplayMemberPath
{
    /// <summary>
    /// MainWindow.xaml の相互作用ロジック
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
    }

    public class MyData
    {
        public string Name { get; set; }
        public Nullable<bool> IsMale { get; set; }
        public string WhatIsCalled { get; set; }
    }
    public class MemberList
    {
        public MemberList()
        {
            MyItems = new ObservableCollection<MyData>
            {
                new MyData{ Name="7of9", IsMale=false, WhatIsCalled="seven"},
                new MyData{ Name="Chakotey", IsMale=true, WhatIsCalled="Number 1"},
                new MyData{ Name="Janeway", IsMale=true, WhatIsCalled="Captain"},
            };
        }
        public ObservableCollection<MyData> MyItems { get; set; }
    }
}
MainWindow.xaml
<Window x:Class="_170605_t1315_DisplayMemberPath.MainWindow"
        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:local="clr-namespace:_170605_t1315_DisplayMemberPath"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <local:MemberList/>
    </Window.DataContext>
    <Grid>
        <ListBox Height="165" Width="300"
            ItemsSource="{Binding Path=MyItems}" DisplayMemberPath="WhatIsCalled"/>
    </Grid>
</Window>