I have just started using WPF forms instead of Windows Forms forms. In a Windows Forms form I could just do:
ComboBox.SelectedValue.toString();
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
}
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());
As a variant in the ComboBox SelectionChanged
event handler:
private void ComboBoxName_SelectionChanged(object send ...
{
string s = ComboBoxName.Items.GetItemAt(ComboBoxName.SelectedIndex).ToString();
}
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;
Well.. I found a simpler solution.
String s = comboBox1.Text;
This way I get the selected value as string.
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();