簡體   English   中英

從組合框WPF中獲取選定的項目

[英]Get selected item from combobox WPF

如何從C#的組合框中獲取選定的值?

我試過這樣的事情:

XAML

<ComboBox x:Name="comboBox" SelectionChanged="comboBox_SelectionChanged_1" >
                <ComboBoxItem Name="Brno" IsSelected="True" Content="Brno"/>
                <ComboBoxItem Name="Item2" Content="Item2"/>
                <ComboBoxItem Name="Item3" Content="Item3"/>
</ComboBox>

C#

private void comboBox_SelectionChanged_1(object sender, 
    System.Windows.Controls.SelectionChangedEventArgs e)

    {
        MessageBox.Show(comboBox.SelectedValue.ToString());

    }

消息框顯示了此System.Windows.Controls.ComboboxItem:Item2

我只需要展示Item2

我怎樣才能做到這一點?

謝謝

您需要從SelectedItem獲取ComboBoxItem並將Content (在您的情況下)轉換為string

private void comboBox_SelectionChanged_1(object sender,
    System.Windows.Controls.SelectionChangedEventArgs e)
{
    string content = ((ComboBoxItem)comboBox.SelectedItem).Content as string;
    if (content != null)
        MessageBox.Show(content);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM