Fang
Fang

Reputation: 2419

Selecting multiple Checkboxes at once

I'm looking for a way to select multiple checkboxes at once in WPF. I'm using the MVVM pattern without any further augments like PRISM. I'm loading data from a MySQL database and binding it to a Data Grid. Then I want to select some of those tables and then add them to another Data Grid. The solution I came up with was creating checkboxes dynamically and binding them to a IsSelected property in my data grid.

<DataGridTemplateColumn 
         Header="" 
         Width="auto" 
         CanUserResize="False" 
         CanUserReorder="False">
                  <DataGridTemplateColumn.CellTemplate>
                      <DataTemplate>
                           <CheckBox x:Name="RadioButtonDatabase" 
                              IsChecked="{Binding IsSelected, 
                              UpdateSourceTrigger=PropertyChanged}" />
                       </DataTemplate>                                             
                 </DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>

The good thing: It works. The bad thing: Each entry in my Datagrid has to be manually clicked, so that IsSelected is updated for each object. I'd like to see a solution that makes multiselection possible (with shift), and possibly a key(space?). Other good ideas are also welcome. Research on the internet didn't yield a satisfying solution.

I'd prefer no answers using codebehind, I'm trying to stick as close to strict MVVM as possible.

Upvotes: 0

Views: 1614

Answers (1)

Kylo Ren
Kylo Ren

Reputation: 8813

You can define Command for your checkbox in your ViewModel(cause I hope you also want binding to reflect on your IsSelected property for each data item when checked):

<CheckBox Command="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGrid}},Path=DataContext.CheckedCommand}" .../>

ViewModel:

   {
      CheckedCommand = new RelayCommand(() => this.CheckAllCheckboxes());           
    }

    public RelayCommand CheckedCommand { get; set; }

    public void CheckAllCheckboxes()
    {
        //set IsSelected true for all items here
    }

Get Relay Command from here

Update: Define a Row style for datagrid that will bind the IsSelected Property of DataGridRow to your Model's any property and then in command action check if row is selected:

 <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="IsSelected" Value="{Binding IsRowSelected}" />
        </Style>
    </DataGrid.RowStyle>

If also want to enable/disable on selection add this binding to checkbox:

IsEnabled="{Binding RelativeSource={RelativeSource AncestorType={x:Type DataGridRow}},Path=IsSelected,Mode=OneWay}"

Upvotes: 1

Related Questions