问题
I have a datagrid with one checkbox column. If anyone clicks on checkbox present in the column header, all check boxes present in that particular column should be checked. How can it be achieved using XAML?
Xaml:
<DataGrid AlternationCount="2" AutoGenerateColumns="False" ItemsSource="{Binding}" Height="325" HorizontalAlignment="Left" Margin="0,178,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="733" >
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<CheckBox Name="colCheckBox" Content="Select All" Width="70" Checked="colCheck_Checked" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="rowCheckBox" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ProjectId" Binding="{Binding ProjectId}" Width="200"/>
<DataGridTextColumn Header="BaselineStartDate" Binding="{Binding BaselineStartDate}" Width="200"/>
<DataGridTextColumn Header="BaselineEndDate" Binding="{Binding BaselineEndDate}" Width="200"/>
</DataGrid.Columns>
</DataGrid>
回答1:
Can you not just data bind the IsChecked
property of the CheckBox
in the Header
straight to the IsChecked
property of the CheckBox
es in the rows? This should do the trick:
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<CheckBox Name="colCheckBox" Content="Select All" Width="70" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox Name="rowCheckBox" IsChecked="{Binding IsChecked,
ElementName=colCheckBox}" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
Of course, this would also allow users to uncheck all of the Checkbox
es from any row and you might not want that. Alternatively, you could use data binding if you had a bool
property in your item class:
<DataGridTemplateColumn>
<DataGridTemplateColumn.Header>
<CheckBox IsChecked="{Binding MasterIsChecked}" Content="Select All" />
</DataGridTemplateColumn.Header>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<CheckBox IsChecked="{Binding IsChecked}" HorizontalAlignment="Center"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
And then update the items from the MasterIsChecked
property in the view model (or code behind):
public bool MasterIsChecked
{
get { return masterIsChecked; }
set
{
masterIsChecked = value;
NotifyPropertyChanged("MasterIsChecked");
foreach (YourClass item in YourItems) item.IsChecked = masterIsChecked;
}
}
来源:https://stackoverflow.com/questions/24905315/how-to-select-all-checkboxes-by-clicking-on-checkbox-column-header-of-a-datagrid