删除单元格内容时删除键被按下
问题描述:
我如何能实现在.NET 4的DataGrid以下任何想法:删除单元格内容时删除键被按下
private void grid_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
DataGridCell cell = e.OriginalSource as DataGridCell;
if (cell == null) { return; }
if (!cell.IsReadOnly && cell.IsEnabled)
{
// Set the cell content (and the property of the object binded to it)
// to null
}
}
}
这种行为应该与任何细胞工作,所以我不不想硬编码列或属性名称。
编辑:解决方案,我想出了:
if (e.Key == Key.Delete)
{
DataGridCell cell = e.OriginalSource as DataGridCell;
if (cell == null) { return; }
if (!cell.IsReadOnly && cell.IsEnabled)
{
TextBlock tb = cell.Content as TextBlock;
if (tb != null)
{
Binding binding = BindingOperations.GetBinding(tb, TextBlock.TextProperty);
if (binding == null) { return; }
BindingExpression exp = BindingOperations.GetBindingExpression(tb, TextBlock.TextProperty);
PropertyInfo info = exp.DataItem.GetType().GetProperty(binding.Path.Path);
if (info == null) { return; }
info.SetValue(exp.DataItem, null, null);
}
}
}
答
这可能是相当复杂的,这取决于电池的模板等
我想像你不得不使用各种BindingOperations
方法(BindingOperations.GetBinding
,BindingOperations.GetBindingExpression
等)弄乱绑定值?
答
有几件事情我必须做的就是这个工作:
-
编辑筛选出时删除按键(找不到一个明显的方式在编辑模式下,如果 检测):
private bool _isEditing = false; private void datagrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) { _isEditing = true; } private void datagrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) { _isEditing = false; }
-
拉手的KEYUP消息(的KeyDown消息是由数据网格处理):
private void dataGrid_KeyUp(object sender, KeyEventArgs e) { if (!_isEditing && e.Key == Key.Delete && Keyboard.Modifiers == ModifierKeys.None) { foreach (var cellInfo in dataGrid.SelectedCells) { var column = cellInfo.Column as DataGridBoundColumn; if (column != null) { var binding = column.Binding as Binding; if (binding != null) BindingHelper.SetSource(cellInfo.Item, binding, null); } } } }
-
使用框架辅助类路由该值= null以底层视图模型
public class BindingHelper: FrameworkElement { public static void SetSource(object source, Binding binding, object value) { var fe = new BindingHelper(); var newBinding = new Binding(binding.Path.Path) { Mode = BindingMode.OneWayToSource, Source = source, }; fe.SetBinding(ValueProperty, newBinding); fe.Value = value; } #region Value Dependency Property public object Value { get { return (object)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(object), typeof(BindingHelper)); #endregion }