[Windows ストアアプリ] ComboBoxで選択されている項目のテキストを取得する 〜その2〜

スポンサーリンク

[Windows ストアアプリ] ComboBoxで選択されている項目のテキストを取得するでは、SelectedItemプロパティをWindows.UI.Xaml.Controls.ContentControl型にキャストして、選択されているテキストを取得する方法について紹介しました

今回はもう1つの方法について説明します。
現在選択されている項目の取得については、前回と同じくSelectedItemプロパティを使用します。前回と異なるのはComboBoxItemにキャストすることです。

次に、キャストしたオブジェクトのContentプロパティを、String型にキャストすれば、現在選択されている項目のテキストを取得することができます。

下記に例を示します。

var selectedItem = (ComboBoxItem)comboBox1.SelectedItem;
string contentString = (string)selectedItem2.Content;

取得したselectedItemの値はnullの場合もあるので、下記のように対策を打つと良いでしょう。

var selectedItem = (ComboBoxItem)comboBox1.SelectedItem;
if (selectedItem == null) return;
string contentString = (string)selectedItem2.Content;
Please follow and like us:

コメント

タイトルとURLをコピーしました