mardi 8 juin 2021

How to get a list of selected items from a listview with checkboxes? (Without code behind)

Sorry if the question is unclear or the answer obvious, I have to work on this project for school without having had a deep dive in c# and WPF.

I built a list view with checkboxes following this

I would like to simply get the list of all items (category) with a thicked checkbox when I click the button "Filter categories".

I found kind of similar questions with answers involving using code behind which I can't do.

enter image description here

<ListView x:Name="ListViewCategories" ItemsSource="{Binding CourseCategories}" >
                <ListView.View>
                    <GridView>
                        <GridViewColumn DisplayMemberBinding="{Binding Title}" Header="Category"/>
                        <GridViewColumn Header="Display" >
                            <GridViewColumn.CellTemplate>
                                <DataTemplate >
                                    <StackPanel Orientation="Horizontal">
                                        <CheckBox IsChecked="{Binding Path=IsSelected, 
                                            RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}"/>
                                    </StackPanel>
                                </DataTemplate>
                            </GridViewColumn.CellTemplate>
                        </GridViewColumn>
                    </GridView>
                </ListView.View>
            </ListView>
        </Grid>
        <Button  Content="Filter Categories" Command="{Binding FilterCategory}" CommandParameter="???" />

Should I pass this to the ViewModel with the button CommandParameter? If yes, how? If no, how can I get the list of selected items in my ViewModel?

The essential of the ViewModel:

namespace Project.ViewModel {
    public class QuestionsViewModel : ViewModelCommon {

        private Course course;
        public Course Course { get => course; set => SetProperty(ref course, value, OnRefreshData); }

        private ObservableCollection<Category> courseCategories;
        public ObservableCollection<Category> CourseCategories {
            get => courseCategories;
            set => SetProperty(ref courseCategories, value);
        }

        public ICommand FilterCategory { get; set; }

        public QuestionsViewModel() : base() {

            FilterCategory = new RelayCommand<List<Category>>(categories => {
                foreach (var c in categories) {
                    Console.WriteLine(c.Title);
                }
            });
        }
   
    }
}

Should I add a bool property display in the "category" model and bind it to the checkbox? If yes, I still don't know how to get a list of all thicked items.




Aucun commentaire:

Enregistrer un commentaire