Search code examples
c#wpfmvvmdatagrid

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


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 ...


Solution

  • <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);
            }