本文就来介绍如何给C1FlexGrid添加CheckBox列,在列头上添加CheckBox,以及选择CheckBox的问题。
在列头添加CheckBox
通过CellFactory功能给ColumnHeader添加CheckBox。
为了添加到列头,需要重写CreateColumnHeaderContent,然后判断ColumnHeader的单元格是布尔类型,就设置CheckBox。
代码参考:
public override void CreateColumnHeaderContent(C1FlexGrid grid, Border bdr, CellRange rng)
{
base.CreateColumnHeaderContent(grid, bdr, rng);
if (grid.ColumnHeaders[rng.Row, rng.Column] is bool)
{
// it does, so create a checkbox to show/edit the value
CheckBox chk = new CheckBox();
chk.IsChecked = (bool?)grid.ColumnHeaders[rng.Row, rng.Column];
chk.VerticalAlignment = VerticalAlignment.Center;
chk.HorizontalAlignment = HorizontalAlignment.Center;
ToolTipService.SetToolTip(chk, "This CheckBox represents a boolean value stored in a grid cell.");
// assign the checkbox to the cell element (a Border)
bdr.Child = chk;
// connect the checkbox so it updates the content of the grid cell
chk.Tag = grid;
chk.AddHandler(CheckBox.ClickEvent, new RoutedEventHandler(chk_Click));
}
}
如果要让CheckBox列的内容也是显示CheckBox,还需要重写CreateCellContent,判断是布尔类型,然后设置checkbox。
代码逻辑和列头设置CheckBox一致。
添加非绑定布尔类型列
通过Columns.Insert方法添加一个布尔类型的列在最左边。
代码参考:
Column c = new Column();
c.DataType = typeof(bool);
_fgBound.Columns.Insert(0,c);
初始化布尔类型值
初始化的时候设置该列的值是false
代码参考:
_fgBound.ColumnHeaders[0, 0] = false;
for (int index = 0; index < _fgBound.Rows.Count; index++)
{
_fgBound[index, 0] = false;
}
选择和反选
当选择/不选择列头的CheckBox的时候,该列的所有行的checkbox会做同步,这个时候就需要在重写的CreateColumnContent添加事件的处理。
当列头的CheckBox被选中或不选的时候,触发该事件,然后循环选择该列所有行。
步骤:
1.首先在CreateColumnContent里添加事件。
代码:
chk.AddHandler(CheckBox.ClickEvent, new RoutedEventHandler(chk_Click));
2.事件处理
private void chk_Click(object sender, EventArgs e)
{
// get the checkbox that was clicked
CheckBox chk = (CheckBox)sender;
// get the grid that owns the checkbox
C1FlexGrid flex = (C1FlexGrid)chk.Tag;
// get the cell that contains the checkbox
Border bdr = (Border)chk.Parent;
////int row = bdr.GetValue(Grid.RowProperty.GlobalIndex);
//int row =(int) bdr.GetValue(Grid.RowProperty);
int col = (int)bdr.GetValue(Grid.ColumnProperty);
//// assign new value to the cell
for (int i = 0; i < flex.Rows.Count; i++)
{
flex[i, col] = chk.IsChecked;
}
}
运行结果如图:
本文的源代码请下载:CheckBoxes.zip (221.14 kb)
更多资源
C1FlexGrid在线英文产品文档地址:
http://helpcentral.componentone.com/nethelp/C1FlexGridWPFSilv/ComponentOne%20FlexGrid%20for%20WPF%20and%20Silverlight.html
如果你对C1FlexGrid感兴趣,请到我们的官网下载最新版本:/download/?pid=6
如果你有疑问,可以到GCDN论坛获得技术支持:http://gcdn.grapecity.com.cn/showforum-138.html
