Search code examples
listviewuwpmultipleselection

UWP How to deal with multiple selections


I'm developing an application where I need to present some options from a service and capture the selection of some of these items from the user. In order to achieve that, I tried to use a ListView with SelectionMode="Multiple" but I've found some troubles with this approach.

Application picture

In the picture above, when the user select an item (from here I will call them "slots") from the left panel, the detail of the selected slot is shown in the right panel. My problem comes dealing with the "handling types" field. As you can see, a slot may have many handling types. I have the need to two-way bind the ListView's SelectedItems property to some property in my ViewModel but this is not possible (by the way, I'm following the MVVM pattern). There's a way to set the selected items from ViewModel and then capture any other selection (or deselection) that the user could made back to my ViewModel. Of course I would prefer a clean an easy solution but at this point any suggestion would be appreciated


Solution

  • We can not assign Binding into the read only property SelectedItems in UWP.

    As a wrokaround, we can define the IsSelected property in the Class, the Class should inherit the INotifyPropertyChanged.

    The class code:

    public class Bundle : INotifyPropertyChanged
    {
        private string _name;
        private bool _isSelected;
    
        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                RaisePropertyChanged("Name");
            }
        }
    
        public bool IsSelected
        {
            get { return _isSelected; }
            set
            {
                _isSelected = value;
                RaisePropertyChanged("IsSelected");
            }
        }
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void RaisePropertyChanged(string name)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(name));
            }
        }
    }
    

    We can set false to the IsMultiSelectCheckBoxEnabled that the CheckBox will not be shown. Then we can add a CheckBox control in the DataTemplate, then we can bind the IsChecked property to the IsSelected.

    For example:

    <ListView Name="MyListView" SelectionMode="Multiple"  IsMultiSelectCheckBoxEnabled="False">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <CheckBox IsChecked="{Binding IsSelected,Mode=TwoWay}"></CheckBox>
                    <TextBlock Text="{Binding Name}" ></TextBlock>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>