identify items in combobox in c # and xaml?

3

I have this combobox in XAML:

<ComboBox x:Name="Tempos" 
              HorizontalAlignment="Left" 
              Height="55" 
              Margin="90,216,0,0" 
              VerticalAlignment="Top" 
              Width="205" SelectionChanged="Tempos_SelectionChanged" >
        <ComboBoxItem Content="2/4" />
        <ComboBoxItem Content="3/4" />
        <ComboBoxItem Content="4/4" />
        <ComboBoxItem Content="5/4" />
        <ComboBoxItem Content="6/4" />
        <ComboBoxItem Content="7/4" />
    </ComboBox>

And in C # I have this method:

private void Tempos_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        resultado.text= Tempos.SelectedIndex.ToString();

    }

I am occupying selectedindex but that is useful if you always know the order, but if the order of the fields in my ComboBox is dynamic, how do I identify them?

    
asked by Edgar Diaz 15.05.2016 в 02:30
source

3 answers

1

If you need an identifier for each item in the combo you should assign it using the SelectedValuePath the theme is that in order to assign it you should indicate a data source

WPF ComboBox and DataBinding: DataContext , ItemsSource, DisplayMemberPath, SelectedItem, SelectedValue & SelectedValuePath

The idea is that you define a class, for example

public class Country
{
   public string Name { get; set; }
   public string Id{ get; set; }
}

and you can indicate it in the control

<ComboBox
   ItemsSource="{Binding Countries, Mode=OneWay}"
   DisplayMemberPath="Name"
   SelectedValue="{Binding ...}"
   SelectedValuePath="Id" />

When assigning the ItemsSource to the Countries property that would be a List<Country> you can indicate properties that define the Value of each element, then you could use the SelectedValue to take the value that identifies the element in the list regardless of the order in to be loaded

    
answered by 18.05.2016 в 23:37
0

You should load an id to be able to identify them, but you can also obtain the value of the selected item in the following way:

string value = Tempos.SelectedValue.ToString();
resultado.text = "Selected: " + value ;
    
answered by 18.05.2016 в 22:45
0

To get the selected item in the comboBox in C # I suggest this:

private void Tempos_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
       resultado.text= Tempos.SelectedItem.ToString();
    }

Do not confuse the Index with the Item. The index is the position of an element, starting with 0. The element (Item) is the object in the collection of objects.

    
answered by 17.07.2016 в 10:21