概要
WPF ComboBoxコントロールでは、ユーザーが選択したアイテムを取得することができます。プログラム上で選択されたアイテムの情報を利用したい場合や、特定の処理を行う際に役立ちます。この記事では、WPF ComboBoxコントロールで選択されたアイテムを取得する方法について説明します。
構文
<ComboBox x:Name="myComboBox"> <ComboBoxItem Content="アイテム1" /> <ComboBoxItem Content="アイテム2" /> </ComboBox>
ComboBoxコントロールで選択されたアイテムを取得するには、ComboBox の SelectedItemプロパティを使用します。プログラム上で取得したアイテムは ComboBoxItem 型として取得されます。必要に応じて ComboBoxItem の Content 8プロパティからテキストを取得し、処理に利用します。
使用例
以下は、ComboBoxに複数のアイテムを定義し、ボタンをクリックすると選択されたアイテムのテキストを表示する例です。
<ComboBox x:Name="myComboBox"> <ComboBoxItem Content="りんご" /> <ComboBoxItem Content="バナナ" /> <ComboBoxItem Content="オレンジ" /> </ComboBox> <Button Content="アイテム取得" Click="GetSelectedItem_Click" /> <TextBlock x:Name="resultTextBlock" />
private void GetSelectedItem_Click(object sender, RoutedEventArgs e) { ComboBoxItem selectedItem = myComboBox.SelectedItem as ComboBoxItem; if (selectedItem != null) { string selectedText = selectedItem.Content.ToString(); resultTextBlock.Text = "選択されたアイテム: " + selectedText; } }
上記のコードでは、ComboBox、Button、TextBlockを配置しています。ボタンのClickイベントハンドラで、選択されたアイテムのテキストを取得し、TextBlockに表示しています。
Please follow and like us:
コメント