wpfxamllistboxlistboxitemsenum-flags

How to bind the multiple selected items of list box in xaml


I have Flags Enum value which I have bound into the item source of listbox. I have used SelectionMode as multiple. I want assign all the selected items of the listbox to a flag Enum property. How can I bind the selected items?

private void ListBox_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
    ListBox list = sender as ListBox;

    this.Weekdays=list.SelectedItems.GetType().GetEnumValues().GetEnumerator()      
                                                    as Weekdays;

}

Here weekdays is Flags-Enum of type Weekdays.I want bind all the selected items of listbox to Weekdays.


Solution

  • The code below is all that you need! list.SelectedItems contains all the selected items, if multiple selection mode is selected. You can track them during selection changed event of list. You can't assign the values to an enum, instead create a list and use that list for storing the selected items using the same data class as the list source.

    private List<DataClass> SelectedItemsList = new List<DataClass>();
    
    if (list.SelectedItems.Count >= 0)
    {
        for (int i = 0; i < list.SelectedItems.Count; i++)
        {
            SelectedItemsList.Add(list.SelectedIndices[i]);
        }
    }