本文主要介绍DataGrid中空白行的使用技巧
实现效果如下:
1.CanUserAddRows属性
CanUserAddRows属性控制DataGrid是否显示空白行,显示空白行的情况下,用户能自行向DataGrid中添加数据。
2.InitializingNewItem事件
通过InitializingNewItem事件可以初始化空白行的默认值。
private void DataGrid_InitializingNewItem(object sender, InitializingNewItemEventArgs e)
{
if (StuList == null || StuList.Count == 0)
{
((Student)e.NewItem).Id = 1;
}
else
{
((Student)e.NewItem).Id = StuList.Max(p => p.Id) + 1;
}
((Student)e.NewItem).Selected = true;
}
3.根据行和列获得指定单元格
在加载表格时,需要将指定单元格进入编辑状态,此时需要根据行和列获得知道单元格,而后为其设置焦点并设置其编辑状态。
private void grd_Loaded(object sender, RoutedEventArgs e)
{
DataGridCell cell = GetCell(0, 2);
if (cell != null)
{
grd.SelectedIndex = 0;
cell.Focus();
grd.BeginEdit();
}
}
/// <summary>
/// 根据行、列索引取的对应单元格对象
/// </summary>
/// <param name="row"></param>
/// <param name="column"></param>
/// <returns></returns>
public DataGridCell GetCell(int row, int column)
{
DataGridRow rowContainer = GetRow(row);
if (rowContainer != null)
{
DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
// try to get the cell but it may possibly be virtualized
DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
if (cell == null)
{
// now try to bring into view and retreive the cell
grd.ScrollIntoView(rowContainer, grd.Columns[column]);
cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
}
return cell;
}
return null;
}
/// <summary>
/// 根据行索引取的行对象
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
public DataGridRow GetRow(int index)
{
DataGridRow row = (DataGridRow)grd.ItemContainerGenerator.ContainerFromIndex(index);
if (row == null)
{
// may be virtualized, bring into view and try again
grd.ScrollIntoView(grd.Items[index]);
row = (DataGridRow)grd.ItemContainerGenerator.ContainerFromIndex(index);
}
return row;
}
/// <summary>
/// 获取指定类型的子元素
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="parent"></param>
/// <returns></returns>
static T GetVisualChild<T>(Visual parent) where T : Visual
{
T child = default(T);
int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
for (int i = 0; i < numVisuals; i++)
{
Visual v = (Visual)VisualTreeHelper.GetChild(parent, i);
child = v as T;
if (child == null)
{
child = GetVisualChild<T>(v);
}
if (child != null)
{
break;
}
}
return child;
}
4.焦点行控制(SelectedIndex)
按回车键时移动到下一行并设置其编辑状态,通过按键事件PreviewKeyUp来触发。
private void grd_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter && grd.CurrentColumn.Header.ToString() == "姓名")
{
grd.SelectedIndex++;
grd.BeginEdit();
}
}
代码
作者:FoolRabbit
出处:http://blog.csdn.net/rabbitsoft_1987
欢迎任何形式的转载,未经作者同意,请保留此段声明!