views:

136

answers:

4

how can I get the selected text on the SelectionChanged event of the comboBox here is my code

<ComboBox x:Name="cboRecordType" Margin="2,0" Height="23" Grid.Column="1" VerticalAlignment="Center" SelectionChanged="ComboBox_SelectionChanged">
            <ComboBoxItem Content="Weight"/>
            <ComboBoxItem Content="Height"/>
            <ComboBoxItem Content="Blood Pressure"/>
            <ComboBoxItem Content="Blood Gulocose"/>
        </ComboBox>

cboRecordType.Text is empty, didn't cantain the selected Text, how to get that

A: 

In your code behind, you need to handle that event like this code: ComboBox SelectionChanged Code Block

/// <summary>

/// Handles the comboBox SelectionChanged event

/// </summary>

/// <param name="sender"></param>

/// <param name="e"></param>

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)

{



}
vodkhang
+1  A: 

In the SelectionChanged event handler, you can either look at the cboRecordType.SelectedItem property on the combobox itself, or you can look at the AddedItems property of the SelectionChangedEventArgs passed into the event handler.

When an item is selected, the item is added to the AddedItems array property of the event args. (multiple items in a multi select case). When an item is deselected, it is added to the RemovedItems array property of the event args.

dthorpe
it will return following value{System.Windows.Controls.ComboBoxItem: Weight}but I only need the Weight how can I get it
Asim Sajjad
@Asim - use SelectedItem.Content ?
Gishu
@Gishu: didn't see any property of content of SelectedItem
Asim Sajjad
@Asim - SelectedItem is defined to return an object. You'd need to cast it to a ComboBoxItem, before accessing its Content property to get the string that you want.
Gishu
I believe you can also try cboRecordType.SelectedValue, which will return the data object type instead of the ComboboxItem. You'll still need to typecast it to the desired type.
dthorpe
Note that eventargs.AddedItems is the preferred pattern, since it will also support multiselection and it tells you which items are coming into selection and which are losing selection (via the RemovedItems array)
dthorpe
A: 

Rather than handling events, you can try the binding approach. For that you need to create a property like this and bind it to your combobox's selected item

private String _selectedItem;
public String SelectedItem
{
    get { return _selectedItem; }
    set
    {
        _selectedItem = value;
        OnPropertyChanged(new PropertyChangedEventArgs("SelectedItem"));
    }
}

<ComboBox SelectedItem="{Binding SelectedItem}" />

SideNote: You can also fill in some collection and bind it to the combobox instead of hardcoding

Veer
A: 

Better try using Command and CommandParametar as part of MVVM implementation.

Levelbit