简体   繁体   中英

Uwp Select ComboboxItem when click on list

I have a form with a 2 items combobox in XAML:

<ComboBox x:Name="cb_Category" PlaceholderText="Category" HorizontalAlignment="Left" Height="40" Margin="20,88,0,0" VerticalAlignment="Top" Width="437" SelectionChanged="cb_Categoria_SelectionChanged">
<ComboBoxItem Content="Products"/>
<ComboBoxItem Content="Services"/>
</ComboBox>

I converted the combobox selected item to string so it can be added to my database and appear on my list.

    private void cb_Category_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (cb_Category.SelectedItem != null)
        {
            var combo = (ComboBox)sender;
            var item = (ComboBoxItem)combo.SelectedItem;
            content = item.Content.ToString();
        }
    }

Now what I want to do is when I select a item in my list, the combobox selects and show the same item. But I have no idea how?

App Sample

As you can see when I click on a Grid Item I get all the values of the item in the textboxes except the combobox

In order to set the List item to your ComboBox you need to set the ItemsSource property as below:

cb_Category.ItemsSource = yourList;

EDIT as per the updated Post

Once your data is loaded you can do something like this on list SelectionChanged :

cb_Category.SelectedIndex = cb_Category.Items.IndexOf(myListView.SelectedItem);

If your List and ComboBox is not sharing the same data structure then you can do something like this:

Your List data structure:

Public Class MyList
{
  public int Property1 {get;set;}
  public int Property2 {get;set;}
  public string Property3 {get;set;} //Property mapped for ComboBox
  public int Property4 {get;set;}
}

Your ComoboBox DataStructure:

Public Class MyComboBox
{
  public int Property1 {get;set;}
  public string Property2 {get;set;} //Property that needs to be display in ComboBox
}

Than on list SelectionChanged first find the item in your ComboBox and then set it's `SelectedIndex'

var selectedItem = myComboBoxDataSource.where(x=>x.Property2.Equals(((MyList)myListView.SelectedItem).Property3));
cb_Category.SelectedIndex = cb_Category.Items.IndexOf(selectedItem);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM