全て
| カテゴリ未分類
| 通常
| 数学
| 投資
| 副業
| 転職・就職
| ブログ
| 株Stock
| VBA
| SharePoint
| REST API
| RenderListDataAsStream
| PowerAutomateDesktop
| Graph API
| PowerApps
| PowerAutomate
| PowerFx
| OfficeScriptオフィススクリプト
| PowerAutomate日時Excel日時相互関係
| PowerShell
| Dataverse
| UiPath
| OneDrive
| LINQ
| VB.NET
| C#.NET
| WPFC#.NET
| Git
カテゴリ:C#.NET
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> ``` ```csharp using 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" に設定して、選択されたアイテムのキーを取得できるようにしています。 お気に入りの記事を「いいね!」で応援しよう
Last updated
2024.03.25 05:47:29
[C#.NET] カテゴリの最新記事
|