トルネード

毛利のメモ書き

UWP 入門 - ComboBox

ComboBox アイテム登録

XAMLで、ComboBox のアイテム登録実装方法です。

<ComboBox HorizontalAlignment="Left" Margin="20,20,0,0" VerticalAlignment="Top" Width="200"  Name="c1">
    <ComboBoxItem>りんご</ComboBoxItem>
    <ComboBoxItem>ごりら</ComboBoxItem>
    <ComboBoxItem>ラッパ</ComboBoxItem>
    <ComboBoxItem IsSelected="True">パンダ</ComboBoxItem>
    <ComboBoxItem>だんご</ComboBoxItem>
</ComboBox>

SelectionChangedイベントでアイテム取得

SelectionChangedは、ComboBoxのアイテム選択で変化があればイベントが発生します。

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (sender != null && t1 != null)
    {
        ComboBox temp = (ComboBox)sender;
        t1.Text = (string)((ComboBoxItem)temp.SelectedValue).Content;
    }
}

Contentをstringへキャストしています。

ComboBox temp = (ComboBox)sender;
t1.Text = (string)((ComboBoxItem)temp.Items[temp.SelectedIndex]).Content;

上記のように書いてもいいのかと思います。

f:id:mojeld:20180727105521g:plain