I can not get the value of a combobox with WPF

-3

I can not get the value of a combobox with WPF. How do I get the value? This is the code for combobox in XAML.

<ComboBox x:Name="cbxCereais" HorizontalAlignment="Left" Margin="145,178,0,0" VerticalAlignment="Top" Width="220">
    <ComboBoxItem Content="Milho"/>
    <ComboBoxItem Content="Soja"/>
    <ComboBoxItem Content="Feijão"/>
</ComboBox>
    
asked by anonymous 08.08.2017 / 14:18

2 answers

1

You need to cast cast to a ComboBoxItem .

var item = cbxCereais.SelectedValue as ComboBoxItem;
var text = item.Content.ToString();

This occurs because items in a ComboBox are treated as ComboBoxItem objects. Doing the cast as reported and accessing the Content property solves the problem.

Finding the Name / Value Property

  

Complementing the answer after having understood what was requested after comments made.

To search for the "value" of a ComboBoxItem, we can use the Name property:

<ComboBox x:Name="cbxCereais" HorizontalAlignment="Left" Margin="145,178,0,0" VerticalAlignment="Top" Width="220">
     <ComboBoxItem Content="Milho" Name="M" />
     <ComboBoxItem Content="Soja" Name="S" />
     <ComboBoxItem Content="Feijão" Name="F" />
</ComboBox>

And in the code:

var item = cbxCereais.SelectedValue as ComboBoxItem;
var text = item.Name;
    
08.08.2017 / 14:57
0

Yes, I did. I understood that in WPF there is the Name property and not Value, so I could not. See the solution:

ComboBoxItem ComboItem = (ComboBoxItem)cbxCereais.SelectedItem;
            string name = ComboItem.Name;
            lblTeste.Content = name;

And so it's in my XAML:

<ComboBox x:Name="cbxCereais" HorizontalAlignment="Left" Margin="145,178,0,0" VerticalAlignment="Top" Width="220" >
            <ComboBoxItem Content="Milho" Name="M"/>
            <ComboBoxItem Content="Soja" Name="S"/>
            <ComboBoxItem Content="Feijão" Name="F"/>
        </ComboBox>
    
08.08.2017 / 14:56