【问题标题】:WPF DataGrid Control Select All OptionWPF DataGrid 控件全选选项
【发布时间】:2016-06-13 09:12:54
【问题描述】:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="5" />               
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>   
<DataGrid x:Name="DtgEntity" Grid.Row="0" ItemsSource="{Binding Entities, Mode=TwoWay}" AutoGenerateColumns="False" ></DataGrid>
<GroupBox Header="Selected Entities" Grid.Row="2" >
<DataGrid x:Name="DtgSelectedEntity" ItemsSource="{Binding SelectedEntities, Mode=TwoWay}" ></DataGrid>
</GroupBox>
</Grid>

这是我的网格控制代码。列名、列数根据对象类型而改变。所以这里我不能指定网格列标签。但网格的第一列总是复选框。

如何将第一列标题更改为复选框。我想为网格的第一列实现全选选项。

【问题讨论】:

  • 实现第一列是复选框列,实现全选非常容易。但每个案例都有自己的方式。如果您能解释得更清楚,请包含您的 DataGrid 的完整 XAML 代码,我可以帮助您。
  • 我添加了完整的 XAML 代码。数据网格列数不固定。列数和名称会根据用户选择而更改。但第一列必须是复选框。选择一个项目后,它移动到第二个网格。单选工作正常。但我需要实现全选选项。
  • 您的 Datagrid 绑定到一个集合包含多种类型的对象或到多个集合,每个集合包含一种类型的对象?您绑定到第一列的属性是否具有相同的名称和类型?
  • 公共 ObservableCollection 实体
  • 好的。如果我要求你揭开更多,似乎很微妙。因此,只需使用 DataGridCheckBoxColumn,更改标题模板,绑定到 checkAll_Property。轻松!

标签: c# wpf datagrid


【解决方案1】:

根据对象类型更改列数。所以这里我不能指定网格列标签

为什么不呢?您可以使用DataGridCheckBoxColumn 指定Columns 标记并将AutoGenerateColumns 设置为true 以根据对象类型生成列。这意味着复选框列将始终出现,其余列将由绑定的ItemsSource 类型生成

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="5" />               
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>   
<DataGrid x:Name="DtgEntity" Grid.Row="0" ItemsSource="{Binding Entities, Mode=TwoWay}" AutoGenerateColumns="False" ></DataGrid>
<GroupBox Header="Selected Entities" Grid.Row="2" >
<DataGrid x:Name="DtgSelectedEntity" ItemsSource="{Binding SelectedEntities, Mode=TwoWay}" AutoGenerateColumns="True" >
    <DataGrid.Columns>
         <DataGridCheckBoxColumn x:Name="myCheckBoxColumn"/>
    </DataGrid.Columns>
</DataGrid>
</GroupBox>
</Grid>

您还可以将DataGridFrozenColumnCount 属性设置为1,以使该列永久滚动。

至于全选功能,SO 上有很多线程可以解决这个问题。这里有一些:

Datagrid Column header should check / uncheck CheckBox’s state depending upon whether all CheckBoxes of a DataGridView column are checked or unchecked

How to Select All CheckBox of a Column by DataGrid Header CheckBox in WPF DataGrid

c# code for select all checkbox in wpf datagrid

希望对你有帮助

【讨论】:

  • 对不起,如果有任何语法错误,这是直接从内存中编写的,还没有机会测试它
猜你喜欢
  • 1970-01-01
  • 2015-07-17
  • 2010-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 2015-06-12
  • 1970-01-01
相关资源
最近更新 更多