azad
azad

Reputation: 65

C# UWP how to get the value of changed ComboBoxItem

In my .xaml file I have my combo box as below:

<ComboBox Name="CLengthCombo" SelectionChanged="ComboBox_SelectionChanged"> <ComboBoxItem Content="24"/> <ComboBoxItem Content="25"/> <ComboBoxItem Content="26" IsSelected="True"/> <ComboBoxItem Content="27"/> </ComboBox> how can I implement my ComboBox_SelectionChanged event so that I can get the content of the comboBoxItem which is changed by user when application is running? Is SelectionChanged event the correct even to use in this case? The below does not work:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { string chosenItem = CLengthCombo.PlaceholderText; } Thanks in advance for your help!

Upvotes: 1

Views: 6703

Answers (3)

Alexandre Lima
Alexandre Lima

Reputation: 324

Get your combobox to work this, c.(...) has SelectedItem, SelectedText ...:

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    var c = sender as ComboBox;

    var item = c.(...);
}

Upvotes: 0

Haithem KAROUI
Haithem KAROUI

Reputation: 1611

You can do it like following

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var comboBoxItem = e.AddedItems[0] as ComboBoxItem;
            if (comboBoxItem == null) return;
            var content = comboBoxItem.Content as string;
            if (content != null && content.Equals("some text"))
            {
                //do what ever you want
            }
        }

Upvotes: 8

hawkstrider
hawkstrider

Reputation: 4341

You can use the SelectedItem property of the combobox

(CLengthCombo.SelectedItem as ComboBoxItem).Content

https://msdn.microsoft.com/library/windows/apps/windows.ui.xaml.controls.combobox.aspx#properties

Upvotes: 2

Related Questions