ComboBox SelectedItem is not showing its value
I have a ComboBox
and its ComboBoxItem
are all generated in run time (programmatically). Whenever there a ComboBox.SelectionChange
, the program will show a MessageBox
showing the selected content of the ComboBox
private void cb2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
MessageBox.Show(cb2.SelectedItem.ToString());
}
However, it is show me:
System.Windows.Controls.ComboBoxItem: Hello World
I only want to show "Hello World" but not the "System...." thing. I tried SelectedValue and that's showing the same thin开发者_StackOverflow中文版g as well.
You need to cast the selected item to a ComboBoxItem and only get its content.
MessageBox.Show((cb2.SelectedItem as ComboBoxItem).Content.ToString());
You should consider using bindings rather than event handlers. This leads to much cleaner code and greater separation of concerns between presentation and process:
Declare your combo as follows:
<ComboBox x:Name="cboCountries" DisplayMemberPath="Name" SelectedItem="{Binding SelectedCountry}" ItemsSource="{Binding Countries}" />
You then bind your ComboBox to a collection on your Window (or preferably a ViewModel):
public Window1()
{
InitializeComponent();
DataContext = this;
this.Countries = new ObservableCollection<Country>();
this.Countries.Add(new Country {Id = 1, Name = "United Kingdom" });
this.Countries.Add(new Country {Id = 1, Name = "United States" });
}
public ObservableCollection<Country> Countries {get; set;}
private Country selectedCountry;
public Country SelectedCountry
{
get { return this.selectedCountry; }
set
{
System.Diagnostics.Debug.WriteLine(string.Format("Selection Changed {0}", value.Name));
this.selectedCountry = value;
}
}
The binding expression on the SelectedValue property of the Combo will cause the property setter on SelectedCountry to fire whenever the selected item changes in the combo.
public class Country
{
public int Id { get; set;}
public string Name {get; set;}
}
精彩评论