Single Click Edit - NULL Reference Exception

Jun 22, 2010 at 5:45 PM

When using the single click edit functions, sometimes I'll get a NULL Reference Exception with Parameter name: Descendant.

CallStack:

   at System.Windows.Media.VisualTreeHelper.IsAncestorOf(DependencyObject ancestor, DependencyObject descendant, Type stopType)
   at System.Windows.Controls.DataGridHelper.ValidateWithoutUpdate(FrameworkElement element)
   at System.Windows.Controls.DataGridColumn.CommitCellEdit(FrameworkElement editingElement)
   at System.Windows.Controls.DataGridColumn.CommitEdit(FrameworkElement editingElement)
   at System.Windows.Controls.DataGridCell.CommitEdit()
   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(CommandBindingCollection commandBindings, Object sender, RoutedEventArgs e, ICommand command, Boolean execute)
   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.OnCurrentCellChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   at System.Windows.DependencyObject.SetCurrentValueInternal(DependencyProperty dp, Object value)
   at System.Windows.Controls.DataGrid.set_CurrentCellContainer(DataGridCell value)
   at System.Windows.Controls.DataGrid.set_FocusedCell(DataGridCell value)
   at System.Windows.Controls.DataGridCell.OnAnyGotFocus(Object sender, RoutedEventArgs e)
   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 e)
   at System.Windows.FrameworkElement.OnGotFocus(RoutedEventArgs e)
   at System.Windows.UIElement.IsFocused_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   at System.Windows.DependencyObject.SetValue(DependencyPropertyKey key, Object value)
   at System.Windows.Input.FocusManager.OnFocusedElementChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)
   at System.Windows.DependencyObject.SetValueCommon(DependencyProperty dp, Object value, PropertyMetadata metadata, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType, Boolean isInternal)
   at System.Windows.DependencyObject.SetValue(DependencyProperty dp, Object value)
   at System.Windows.Input.FocusManager.SetFocusedElement(DependencyObject element, IInputElement value)
   at System.Windows.Input.KeyboardNavigation.UpdateFocusedElement(DependencyObject focusTarget)
   at System.Windows.FrameworkElement.OnGotKeyboardFocus(Object sender, KeyboardFocusChangedEventArgs e)
   at System.Windows.Input.KeyboardFocusChangedEventArgs.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.KeyboardDevice.ChangeFocus(DependencyObject focus, Int32 timestamp)
   at System.Windows.Input.KeyboardDevice.TryChangeFocus(DependencyObject newFocus, IKeyboardInputProvider keyboardInputProvider, Boolean askOld, Boolean askNew, Boolean forceToNullIfFailed)
   at System.Windows.Input.KeyboardDevice.Focus(DependencyObject focus, Boolean askOld, Boolean askNew, Boolean forceToNullIfFailed)
   at System.Windows.Input.KeyboardDevice.Focus(IInputElement element)
   at System.Windows.UIElement.Focus()
   at Pcis.Emr.Main.Views.SectionRxView.StartDataGridEdit(DataGridCell cell) in C:\Projects\PCIS\EMRv0.2\Pcis.Emr\Pcis.Emr.Main\Views\SectionRxView.xaml.cs:line 133
   at Pcis.Emr.Main.Views.SectionRxView.DataGridCell_PreviewMouseLeftButtonDown(Object sender, MouseButtonEventArgs e) in C:\Projects\PCIS\EMRv0.2\Pcis.Emr\Pcis.Emr.Main\Views\SectionRxView.xaml.cs:line 119
   at System.Windows.Input.MouseButtonEventArgs.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.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   at System.Windows.UIElement.OnPreviewMouseDownThunk(Object sender, MouseButtonEventArgs e)
   at System.Windows.Input.MouseButtonEventArgs.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.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   at MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

Code Behind

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();   /// ****Blowing up here
      }

      DataGrid dataGrid = cell.TryFindVisualParent<DataGrid>();

      if (dataGrid != null)
      {
        if (dataGrid.SelectionUnit != DataGridSelectionUnit.FullRow)
        {
          if (!cell.IsSelected)
          {
            cell.IsSelected = true;
          }
        }
        else
        {
          DataGridRow row = cell.TryFindVisualParent<DataGridRow>();

          if (row != null && !row.IsSelected)
          {
            row.IsSelected = true;
          }
        }
      }
  }

Xaml

<DataGrid Grid.Row="1" Grid.ColumnSpan="2" x:Name="medList" 
                                ItemsSource="{Binding Prescriptions}"
                                AutoGenerateColumns="False" 
                                GridLinesVisibility="All" 
                                VerticalGridLinesBrush="LightGray" 
                                SelectionUnit="FullRow" 
                                CanUserAddRows="False"
                                SelectionMode="Single"
                                HorizontalGridLinesBrush="LightGray"
                                Background="White"
                                Foreground="#FF042271"
                                ColumnHeaderStyle="{StaticResource DefaultColumnHeaderStyle}"                                
                                RowStyle="{StaticResource dgRowStyle}"
                                ColumnDisplayIndexChanged="ColumnDisplayIndexChanged"
                                common:DataGridUtil.IsGridSortable="True"
                                >
                      <DataGrid.Resources>
                        <Style TargetType="{x:Type DataGridCell}">
                            <EventSetter Event="UIElement.PreviewMouseLeftButtonDown" Handler="DataGridCell_PreviewMouseLeftButtonDown"/>
                            <EventSetter Event="UIElement.PreviewKeyDown" Handler="NewRxDataGrid_PreviewKeyDown"/>
                            <EventSetter Event="UIElement.KeyUp" Handler="KeyCellUp"/>
                        </Style>
                     </DataGrid.Resources>
                    <DataGrid.Columns>
                        <DataGridTemplateColumn SortMemberPath="Script.Sig.FormattedSig" common:DataGridUtil.SortBinding="Script.Sig.FormattedSig" Header="Sig" x:Name="sig" MinWidth="100" Width="Auto">
                            <DataGridTemplateColumn.CellEditingTemplate>
                                <DataTemplate>
                                    <Border x:Name="CellBorder">
                                        <Grid>
                                            <Grid.ColumnDefinitions>
                                                <ColumnDefinition Width="*"/>
                                                <ColumnDefinition Width="Auto"/>
                                            </Grid.ColumnDefinitions>

                                            <Button HorizontalAlignment="Left"  Style="{StaticResource NoBorderButton}" IsEnabled="{Binding Script.Sig.HasValue}" MaxHeight="20" x:Name="selectText" Tag="{Binding}">
                                                <StackPanel Orientation="Horizontal">
                                                    <TextBlock x:Name="elementText" Text="{Binding Script.Sig.FormattedSig}" HorizontalAlignment="Left" MaxHeight="20" MinWidth="100"/>
                                                    <Polygon Margin="3,0"  Points="0,0 7.5,7.5 15,0" Fill="AntiqueWhite" HorizontalAlignment="Left" VerticalAlignment="Center"/>
                                                </StackPanel>
                                            </Button>
                                            <Popup x:Name="popup" StaysOpen="False" PlacementTarget="{Binding ElementName=CellBorder}" Placement="Bottom">
                                                <Border BorderBrush="LightGray" BorderThickness="1" Background="{x:Static SystemColors.InfoBrush}">
                                                    <StackPanel Orientation="Horizontal">
                                                        <ComboBox x:Name="amount" SelectedItem="{Binding Script.Sig.Amount}" Margin="3" ItemsSource="{x:Static data:Sig.Amounts}" KeyDown="Amount_KeyDown"/>
                                                        <ComboBox x:Name="form" SelectedItem="{Binding Script.Sig.Form}" Margin="3" ItemsSource="{x:Static data:Sig.Forms}"/>
                                                        <ComboBox x:Name="routes" SelectedItem="{Binding Script.Sig.Route}" Margin="3" ItemsSource="{x:Static data:Sig.Routes}"/>
                                                        <ComboBox x:Name="frequencies" SelectedItem="{Binding Script.Sig.Frequency}" Margin="3" ItemsSource="{x:Static data:Sig.Frequencies}" KeyDown="Frequency_KeyDown"/>
                                                    </StackPanel>
                                                </Border>
                                            </Popup>
                                        </Grid>
                                    </Border>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellEditingTemplate>
                            <DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Text="{Binding Script.Sig.FormattedSig}" HorizontalAlignment="Left" MaxHeight="20" MinWidth="100" />
                                        <Polygon Margin="3,0"  Points="0,0 7.5,7.5 15,0" Fill="AntiqueWhite" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                                    </StackPanel>
                                </DataTemplate>
                            </DataGridTemplateColumn.CellTemplate>
                        </DataGridTemplateColumn>
                        <DataGridTextColumn common:DataGridUtil.SortBinding="Script.Provider" Header="Prescribed By"  MinWidth="100" Width="Auto" Binding="{Binding Script.Provider}" />
                    </DataGrid.Columns>
                </DataGrid>

 

The exception occurs when I click between the Prescribed By header and the Sig header.  If you click on the sig header and then back to the prescribed by header do this a couple of time you should be able to re-create

 

Thanks