您的位置:首页 > 其它

DataGrid双击选中单元格该为单击

2012-09-27 17:10 337 查看
By default, end users must double-click a cell in the DataGrid to enter edit mode. In certain cases, it may be more desirable for cells to enter edit mode with a single mouse click (for example, when editing a CheckBox). Use the code snippets below to implement
single-click editing in your DataGrid.

To apply single-click editing to all cells in the DataGrid

1. Paste the style below into the Resources of your DataGrid

2. Paste the method into the code behind

To apply single-click editing to only certain cells in the DataGrid

1. Set an x:Key on the Style (ex. <Style x:Key="SingleClickEditing" TargetType="{x:Type dg:DataGridCell}">)

2. Paste the style into the Resources of your DataGrid

3. Apply the style to the CellStyle property of the columns which you'd like to have single click editing (ex. <dg:DataGridCheckBoxColumn CellStyle="{StaticResource SingleClickEditing}"/>)

4. Paste the method into the code behind

<!--
SINGLE CLICK EDITING
-->
<Style TargetType="{x:Type dg:DataGridCell}">
<EventSetter Event="PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"></EventSetter>
</Style>

//
// SINGLE CLICK EDITING
//
private void DataGridCell_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
DataGridCell cell = sender as DataGridCell;
if (cell != null && !cell.IsEditing && !cell.IsReadOnly)
{
if (!cell.IsFocused)
{
cell.Focus();
}
DataGrid dataGrid = FindVisualParent<DataGrid>(cell);
if (dataGrid != null)
{
if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
{
if (!cell.IsSelected)
cell.IsSelected = true;
}
else
{
DataGridRow row = FindVisualParent<DataGridRow>(cell);
if (row != null && !row.IsSelected)
{
row.IsSelected = true;
}
}
}
}
}

static T FindVisualParent<T>(UIElement element) where T : UIElement
{
UIElement parent = element;
while (parent != null)
{
T correctlyTyped = parent as T;
if (correctlyTyped != null)
{
return correctlyTyped;
}

parent = VisualTreeHelper.GetParent(parent) as UIElement;
}
return null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: