问题描述:

I am trying to set the selected item in my silverlight combobox from a string.

In this example lets say I have a combobox named "MyComboBox" as follows:

<ComboBox Height="23" x:Name="MyComboBox" Width="200" HorizontalAlignment="Left">

<ComboBoxItem Tag="0" Content="Pizza" IsSelected="True"/>

<ComboBoxItem Tag="1" Content="Soda"/>

<ComboBoxItem Tag="2" Content="Wings"/>

<ComboBoxItem Tag="3" Content="Bread Sticks"/>

</ComboBox>

I am randomly selecting a string value above from a list to simulate a users saved preference. The problem I am facing is trying to grab the index of "MyComboBox" from a string.

I've tried using MyComboBox.items wtih LINQ but that has taken me nowhere.

There are some similar questions here on stack overflow but none of these have been answered.

网友答案:

If you have a reason that you have to wrap the strings in ComboBoxItem then this should work.

MyComboBox.Items.SelectedItem = 
    MyComboBox.Items.SingleOrDefault(c => (c as ComboBoxItem).Content == myString);

I would recommend to not directly insert ComboBoxItem and set items to String or setup a collection in code and bind to it.

网友答案:

You can achieve this by using the following.

SetSelectedItem("Pizza");

/// Set selected item as string.

    private void SetSelectedItem(string selectedString)
    {
        Func<ComboBoxItem, ComboBoxItem> selectionFunc = (item) =>
        {
            if(item.Content.ToString() == selectedString)
                return item;
            return null;
        };

        this.MyComboBox.SelectedItem = MyComboBox.Items.Select(s => selectionFunc(s as ComboBoxItem)).FirstOrDefault();
    }
网友答案:

Hi i am applied function for encountred index in Combobox

private int Search_Item_Return_Index(ComboBox combo, string Search)
     {
         int index=-1;

         foreach (ComboBoxItem item in combo.Items)
         {
             index++;
             string var = item.Content.ToString() ;
             if (var.Equals(Search))
             {
                 return index;
             }

         }


         return index;

     }
网友答案:

If you are putting strings into the combobox then you can use

MyComboBox.Items.IndexOf("Pizza")
网友答案:

I see, you can add a name to the xaml

<ComboBoxItem Tag="0" Name="CBIPizza" IsSelected="True" Content="Pizza" />

then use

MyComboBox.Items.IndexOf(CBIPizza);

or... Make the items strings instead using

  <ComboBox Name="MyComboBox>
    <ComboBox.Items>
            <sys:String>Pizza</sys:String>
            <sys:String>Bread Sticks</sys:String>
      </ComboBox.Items>

which of course requires defining

xmlns:sys="clr-namespace:System;assembly=mscorlib"

Then the original example would work

相关阅读:
Top