Удалить содержимое ячейки в WPF DataGrid при нажатии клавиши Delete - PullRequest
1 голос
/ 10 декабря 2010

Любая идея о том, как я могу достичь следующего в .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
        }
    }
}

Это поведение должно работать с любой ячейкой, поэтому я не хочу жестко кодировать имена столбцов или свойств.1004 *

РЕДАКТИРОВАТЬ: Решение, которое я придумал:

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

Ответы [ 2 ]

3 голосов
/ 05 сентября 2012

Мне нужно было сделать несколько вещей, чтобы заставить это работать:

  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. Обработка сообщения 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);
               }
            }
        }
    }
    
  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
    }
    
0 голосов
/ 10 декабря 2010

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

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...