Home > Software engineering >  How to do select all and unselect all of a WPF datagrid on a button click using MVVM?
How to do select all and unselect all of a WPF datagrid on a button click using MVVM?

Time:11-14

How can I select all rows/unselect all rows of a WPF datagrid on a button click without messing up the MVVM pattern ?

Currently I doing something like this:

XAML

<Button Command="{Binding SelButtonClicked}" .../>

and in the Mainviewmodel

public RelayCommand SelButtonClicked { get; set; }
...
Public Mainviewmodel()
{
  SelButtonClicked = new RelayCommand(SelUnsel);
}
...
public void SelUnsel(object param)
        {
            var win = Application.Current.Windows
                .Cast<Window>()
                .FirstOrDefault(window => window is MainWindow) as MainWindow;
            
            if (win.myGrid.SelectedItems.Count > 0)
            {
                win.myGrid.UnselectAll();
            }
            else
            {
                win.myGrid.SelectAll();
            }
        }

But I'm pretty sure it is not the MVVM way ...

CodePudding user response:

<Button Command="{Binding SelButtonClicked}"
        CommandParameter="{Binding SelectedItems, ElementName=dataGrid}"
        .../>
        private void SelUnsel(object param)
        {
            IList list = (IList) param;
            list.Clear();
        }

how do I do the opposite i.e. select all ?

        private void SelAll(object param)
        {
            IList list = (IList) param;
            foreach(var item in SomeItemCollection)
                list.Add(item);
        }

CodePudding user response:

So, this is my final implementation using @EldHasp 's shown method.

<Button Command="{Binding SelButtonClicked}"
        CommandParameter="{Binding SelectedItems, ElementName=dataGrid}"
        .../>

public void SelUnsel(object param)
{
            IList list = (IList) param;
            
            if (list.Count > 0)
            {
                list.Clear();
            }
            else
            {
                foreach(var item in dgItemSource)
                    list.Add(item);
            }
}
  • Related