C# WPF で ComboBox にリストデータを表示する際に、キーと値を別に設定する方法
C# WPF で ComboBox にリストデータを表示する際に、キーと値を別に設定する方法として、以下の手順に従うことができます。1. データをキーと値のペアとして持つクラスを作成します。2. ComboBox の DisplayMemberPath プロパティを使用して表示するプロパティを指定します。3. ComboBox の SelectedValuePath プロパティを使用して選択された値のプロパティを指定します。以下にサンプルコードを示します。```xml<Window x:Class="ComboBoxWithKeyValuePair.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="ComboBox with Key-Value Pair" Height="250" Width="350"> <Grid> <ComboBox x:Name="comboBox" Width="200" VerticalAlignment="Center" HorizontalAlignment="Center" DisplayMemberPath="Value" SelectedValuePath="Key" SelectedIndex="0" SelectionChanged="ComboBox_SelectionChanged"/> </Grid></Window>``````csharpusing System.Collections.Generic;using System.Windows;namespace ComboBoxWithKeyValuePair{ public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); // ComboBox にデータを追加 List<KeyValuePair<int, string>> dataList = new List<KeyValuePair<int, string>> { new KeyValuePair<int, string>(1, "Option 1"), new KeyValuePair<int, string>(2, "Option 2"), new KeyValuePair<int, string>(3, "Option 3"), new KeyValuePair<int, string>(4, "Option 4"), new KeyValuePair<int, string>(5, "Option 5") }; comboBox.ItemsSource = dataList; comboBox.SelectedIndex = 0; // デフォルトで選択される項目を設定 } private void ComboBox_SelectionChanged(object sender, RoutedEventArgs e) { if (comboBox.SelectedItem != null) { KeyValuePair<int, string> selectedItem = (KeyValuePair<int, string>)comboBox.SelectedItem; MessageBox.Show($"Selected option: Key={selectedItem.Key}, Value={selectedItem.Value}"); } } }}```このコードでは、KeyValuePair<int, string> を使用して、キーと値のペアを表現しています。ComboBox の DisplayMemberPath プロパティを "Value" に設定し、表示されるテキストを Value プロパティの値に設定します。また、SelectedValuePath プロパティを "Key" に設定して、選択されたアイテムのキーを取得できるようにしています。