Get selected value from combo box in C# WPF

后端 未结 21 606
粉色の甜心
粉色の甜心 2020-12-08 09:29

I have just started using WPF forms instead of Windows Forms forms. In a Windows Forms form I could just do:

ComboBox.SelectedValue.toString();
相关标签:
21条回答
  • 2020-12-08 09:56

    XAML:

    <ComboBox Height="23" HorizontalAlignment="Left" Margin="19,123,0,0" Name="comboBox1" VerticalAlignment="Top" Width="33" ItemsSource="{Binding}" AllowDrop="True" AlternationCount="1">
        <ComboBoxItem Content="1" Name="ComboBoxItem1" />
        <ComboBoxItem Content="2" Name="ComboBoxItem2" />
        <ComboBoxItem Content="3" Name="ComboBoxItem3" />
    </ComboBox>
    

    C#:

    if (ComboBoxItem1.IsSelected)
    {
        // Your code
    }
    else if (ComboBoxItem2.IsSelected)
    {
        // Your code
    }
    else if(ComboBoxItem3.IsSelected)
    {
        // Your code
    }
    
    0 讨论(0)
  • 2020-12-08 10:00

    Ensure you have set the name for your ComboBox in your XAML file:

    <ComboBox Height="23" Name="comboBox" />
    

    In your code you can access selected item using SelectedItem property:

    MessageBox.Show(comboBox.SelectedItem.ToString());
    
    0 讨论(0)
  • 2020-12-08 10:00

    As a variant in the ComboBox SelectionChanged event handler:

    private void ComboBoxName_SelectionChanged(object send ...
    {
        string s = ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();
    }
    
    0 讨论(0)
  • 2020-12-08 10:05

    It depends what you bound to your ComboBox. If you have bound an object called MyObject, and have, let's say, a property called Name do the following:

    MyObject mo = myListBox.SelectedItem as MyObject;
    return mo.Name;
    
    0 讨论(0)
  • 2020-12-08 10:06

    Well.. I found a simpler solution.

    String s = comboBox1.Text;
    

    This way I get the selected value as string.

    0 讨论(0)
  • 2020-12-08 10:09

    My XAML is as below:

    <ComboBox Grid.Row="2" Grid.Column="1" Height="25" Width="200" SelectedIndex="0" Name="cmbDeviceDefinitionId">
        <ComboBoxItem Content="United States" Name="US"></ComboBoxItem>
        <ComboBoxItem Content="European Union" Name="EU"></ComboBoxItem>
        <ComboBoxItem Content="Asia Pacific" Name="AP"></ComboBoxItem>
    </ComboBox>
    

    The content is showing as text and the name of the WPF combobox. To get the name of the selected item, I have follow this line of code:

    ComboBoxItem ComboItem = (ComboBoxItem)cmbDeviceDefinitionId.SelectedItem;
    string name = ComboItem.Name;
    

    To get the selected text of a WPF combobox:

    string name = cmbDeviceDefinitionId.SelectionBoxItem.ToString();
    
    0 讨论(0)
提交回复
热议问题