2010-12-10 1 views
1

Любая идея о том, как я могу достичь следующего в .Net 4 DataGrid:содержание Удаление ячейки в DataGrid WPF, когда Delete нажата клавиша

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 
     } 
    } 
} 

Такое поведение должно работать с любой клеткой, поэтому я не Не хотите жестко указывать имена столбцов или свойств.

EDIT: Решение я придумал:

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); 
      } 
    } 
} 

ответ

0

Это может быть довольно сложным, в зависимости от шаблона клетки и т.д.

Я полагаю, вы должны были бы использовать различные BindingOperations методы (BindingOperations.GetBinding, BindingOperations.GetBindingExpression и т. Д.), Чтобы испортить связанное значение?

3

Там несколько вещей, которые я должен был сделать, чтобы получить эту работу:

  1. Отфильтровать удаления нажатий клавиш при редактировании (не мог найти очевидный способ обнаружить, если в режиме редактирования):

    private bool _isEditing = false; 
    private void datagrid_BeginningEdit(object sender, DataGridBeginningEditEventArgs e) 
    { _isEditing = true; } 
    
    private void datagrid_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e) 
    { _isEditing = false; } 
    
  2. Handle сообщение KeyUp (KeyDown сообщение было обработано с помощью DataGrid):

    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); 
          } 
         } 
        } 
    } 
    
  3. Используйте рамочное вспомогательный класс для маршрутизации значение = 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 
    }