DataGridCheckBoxColumn在Xaml中实现检查和取消选中功能

时间:2015-11-05 22:04:48

标签: wpf xaml

我的应用有一个DataGridCheckBoxColumn,标题是一个复选框。 我正在努力实现以下功能:

  1. 当用户检查标题复选框时,应检查整列。
  2. 当用户取消选中列标题时,应取消选中整个DataGridCheckBoxColumn。
  3. 检查整列并且用户取消选中一个单元格时,标题也应取消选中。
  4. 是否可以通过编写代码来实现此功能?

    这是我用来创建DataGridCheckbox列的代码

     <DataGridCheckBoxColumn
         Binding="{Binding Path=IsSelected,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         ElementStyle="{StaticResource DataGridCheckBoxStyle}" >
         <DataGridCheckBoxColumn.Header>
             <CheckBox
                 IsChecked="{Binding Path=Data.AllItemsSelected, Source={StaticResource proxy}}"
                 IsEnabled="{Binding Path=IsBusy, Converter={StaticResource BooleanNotConverter}}" />
         </DataGridCheckBoxColumn.Header>
     </DataGridCheckBoxColumn>
    

    提前致谢

1 个答案:

答案 0 :(得分:0)

您应使用DataGridRowHeader而不是使用列的复选框,而{I}列用于SelectAll列。

<DataGrid>
    <DataGrid.RowHeaderTemplate>
        <DataTemplate>
            <CheckBox x:Name="selectCheckBox"
                      Margin="2,0,0,0"
                      IsChecked="{Binding Path=IsSelected, 
                                          Mode=TwoWay,
                                          RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type DataGridRow}}}">
            </CheckBox>
        </DataTemplate>
    </DataGrid.RowHeaderTemplate>

    <DataGrid.CommandBindings>
        <CommandBinding Command="SelectAll" Executed="CommandBinding_Executed" />
    </DataGrid.CommandBindings>
</DataGrid>

默认情况下,标题按钮仅用作SelectAll按钮。允许它取消选择DataGrid.CommandBindings也被声明为更改SelectAll按钮的行为。在后面的代码中,声明以下处理程序:

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    var dg = (DataGrid)sender;

    // You might want to do some null checking here

    // If all items are selected, then unselect all
    if (dg.SelectedItems.Count == dg.Items.Count)
        dg.UnselectAll();       
    else
        dg.SelectAll();

    e.Handled = true;
}