Search code examples
c#xamlwinrt-xamlwin-universal-app

Finding the Index of an item in a combo box XAML/C#/WinRT


so I've done a lot of research and tried many people's solutions, and nothing seems to work and I can't figure out why. I'm trying to find the Index of an item in my ComboBox:

string Index = programType.Items.IndexOf("Lose Weight").ToString();

Index is always "-1" even though there is definitely an item that has Content/Tag of "Lose Weight":

<ComboBox x:Name="programType" Header="Desired goal:" HorizontalAlignment="Left" Grid.Row="5" Grid.Column="1" Margin="30,0,0,0" Grid.ColumnSpan="2" VerticalAlignment="Top" Width="200" PlaceholderText="Desired Goal">
    <ComboBoxItem Content="Lose Weight" Tag="Lose Weight" IsSelected="True" />
    <ComboBoxItem Content="Get Healthier" Tag="Get Healthier"/>
    <ComboBoxItem Content="Get Stronger" Tag="Get Stronger"/>
    <ComboBoxItem Content="Cardio Booster" Tag="Cardio Booster"/>
</ComboBox>

As far as I can tell it should be working? I must be doing something wrong, any tips? Thanks!


Solution

  • When you add items this way, Items property contains objects of type ComboBoxItem. Use the following code to get the list of strings:

    int index = programType.Items
        .Cast<ComboBoxItem>()
        .Select(c => (string)c.Content)
        .ToList()
        .IndexOf("Lose Weight");