動作環境
Windows 7 Pro (32bit)
Microsoft Visual Studio 2017 Community
Sublime Text 2
@ WPF 4.5入門 by 大田一希さん
No.4260 / 9985
ComboBoxの基本的な使い方は、ItemsSourceプロパティにオブジェクトのコレクションを設定して、ItemTemplateで見た目を定義する方法になります。
試してみた
XAML
<Window x:Class="_170425_t2100_combobox.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:_170425_t2100_combobox"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox x:Name="comboBox1" Height="40">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Name}/>
<TextBox Text="{Binding Age}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
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;
namespace _170425_t2100_combobox
{
/// <summary>
/// MainWindow.xaml の相互作用ロジック
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var data = new List<Person>();
data.Add(new Person { Name = "item1", Age = 10 });
data.Add(new Person { Name = "item2", Age = 20 });
data.Add(new Person { Name = "item3", Age = 30 });
comboBox1.ItemsSource = data;
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
}
見た目が悪い。
プロダクションコードで使うようにする場合、上記のおかしな表示を回避する方法を見つけないといけない。
IsEditable
IsEditableをTrueにし、TextSearch.TextPathをNameに設定してみた。
XAML
<Window x:Class="_170425_t2100_combobox.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:_170425_t2100_combobox"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525">
<Grid>
<ComboBox x:Name="comboBox1" IsEditable="True"
TextSearch.TextPath="Name"
Height="40">
<ComboBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox Text="{Binding Name}"/>
<TextBox Text="{Binding Age}"/>
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</Grid>
</Window>
選択後の表示がNameのみの表示になってしまった。