Вход в режим прерывания по событию DataGrid CellEditEnding - PullRequest
0 голосов
/ 28 августа 2018

Я снимаю, когда пользователь заканчивает редактирование ячейки в моем DataGrid в WPF, и пытаюсь обновить DataTable, чтобы отразить это.

Однако код входит в «режим прерывания», а затем просто закрывается.

private void DataGridView1_CellEditEnding(object sender, DataGridCellEditEndingEventArgs e)
{
    DataGridColumn col1 = e.Column;
    DataGridRow row1 = e.Row;
    int row_index = ((System.Windows.Controls.DataGrid)sender).ItemContainerGenerator.IndexFromContainer(row1);
    int col_index = col1.DisplayIndex;
    var itemtext = ((System.Windows.Controls.TextBox)e.EditingElement).Text;
    if(dt.Rows[row_index].ItemArray[col_index].ToString()!= itemtext)
    {
        DataGridView1.DataContext = null;
        dt.Rows[row_index][col_index] = itemtext;
        DataGridView1.DataContext = dt;
    }          
}

Кто-нибудь знает, что может быть причиной этого?

dt является DataTable.

Причина, по которой я обновляю DataContext каждый раз, когда редактируется ячейка, состоит в том, что у меня есть код, который говорит, что если значение ячейки превышает 33 символа, чтобы закрасить ячейку красным, поэтому всякий раз, когда ячейка редактируется, я хочу Цвет для обновления, чтобы отразить это.

UPDATE

Я посмотрел в выходной отладке и обнаружил следующую ошибку

Произошло необработанное исключение типа «System.ArgumentNullException» в PresentationCore.dll Значение не может быть нулевым.

Unhandled Exception: System.ArgumentNullException: Value cannot be null.
    Parameter name: element
   at 
  System.Windows.Automation.Peers.UIElementAutomationPeer.FromElement(UIElement element)
   at System.Windows.Controls.DataGrid.CellAutomationValueHolder.TrackValue()
   at System.Windows.Controls.DataGrid.UpdateCellAutomationValueHolder(DataGridCell cell)
   at System.Windows.Controls.DataGrid.OnExecutedCommitEdit(ExecutedRoutedEventArgs e)
   at System.Windows.Controls.DataGrid.OnExecutedCommitEdit(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandBinding.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.CommandManager.ExecuteCommandBinding(Object sender, ExecutedRoutedEventArgs e, CommandBinding commandBinding)
   at System.Windows.Input.CommandManager.FindCommandBinding(Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   at System.Windows.Input.CommandManager.OnExecuted(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.UIElement.OnExecutedThunk(Object sender, ExecutedRoutedEventArgs e)
   at System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler(Delegate genericHandler, Object target)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.RoutedCommand.ExecuteImpl(Object parameter, IInputElement target, Boolean userInitiated)
   at System.Windows.Input.RoutedCommand.Execute(Object parameter, IInputElement target)
   at System.Windows.Controls.DataGrid.EndEdit(RoutedCommand command, DataGridCell cellContainer, DataGridEditingUnit editingUnit, Boolean exitEditMode)
   at System.Windows.Controls.DataGrid.CommitAnyEdit()
   at System.Windows.Controls.DataGrid.OnEnterKeyDown(KeyEventArgs e)
   at System.Windows.Controls.DataGrid.OnKeyDown(KeyEventArgs e)
   at System.Windows.UIElement.OnKeyDownThunk(Object sender, KeyEventArgs e)
   at System.Windows.Input.KeyEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   at System.Windows.Input.InputManager.ProcessStagingArea()
   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   at System.Windows.Interop.HwndKeyboardInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawKeyboardActions actions, Int32 scanCode, Boolean isExtendedKey, Boolean isSystemKey, Int32 virtualKey)
   at System.Windows.Interop.HwndKeyboardInputProvider.ProcessKeyAction(MSG& msg, Boolean& handled)
   at System.Windows.Interop.HwndSource.CriticalTranslateAccelerator(MSG& msg, ModifierKeys modifiers)
   at System.Windows.Interop.HwndSource.OnPreprocessMessage(Object param)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   at System.Windows.Interop.HwndSource.OnPreprocessMessageThunk(MSG& msg, Boolean& handled)
   at System.Windows.Interop.HwndSource.WeakEventPreprocessMessage.OnPreprocessMessage(MSG& msg, Boolean& handled)
   at System.Windows.Interop.ThreadMessageEventHandler.Invoke(MSG& msg, Boolean& handled)
   at System.Windows.Interop.ComponentDispatcherThread.RaiseThreadMessage(MSG& msg)
   at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   at System.Windows.Application.RunDispatcher(Object ignore)
   at System.Windows.Application.RunInternal(Window window)
   at System.Windows.Application.Run(Window window)
   at System.Windows.Application.Run()
   at DMHotFolderMain.App.Main()

Я обнаружил, что это происходит только в том случае, если DataContext равен нулю, а обновление DataTable вызывается вместе.

Я попытался закомментировать строки, и они работают самостоятельно, но не вместе.

1 Ответ

0 голосов
/ 28 августа 2018

Я бы порекомендовал вам использовать ValidationRule, потому что с ним гораздо проще обращаться. Вы можете предоставить настраиваемую визуальную обратную связь (например, изменить цвет фона) в зависимости от ввода пользователя.

public class TextLengthValidationRule : ValidationRule
{
    public override ValidationResult Validate(object value,
        System.Globalization.CultureInfo cultureInfo)
    {
        var str = (value as BindingGroup).Items[0] as string;
        if (str.Length > 33)
        {
            return new ValidationResult(false,
                "Text must be shorter than 33 chars");
        }
        else
        {
            return ValidationResult.ValidResult;
        }
    }
}

Ознакомьтесь с Как выполнить проверку с помощью элемента управления DataGrid .

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