Используйте Popup в EditingTemplateCell: Message = Value не может быть нулевым. Имя параметра: потомок - PullRequest
3 голосов
/ 22 сентября 2010

Я использую WPF DataGrid и помещаю DataGridTemplateColumn.Так как столбец должен выполнять редактирование для сложного типа (это объект), я решил добавить тумблер, который открывает всплывающее окно.Код следующий:

                <DataTemplate>
                    <Grid>
                        <ToggleButton Grid.Column="2" x:Name="tb" Focusable="false" IsChecked="False" ClickMode="Press"  Content="Edit values" />
                        <Popup IsOpen="{Binding ElementName=tb, Path=IsChecked, Mode=OneWay}" Placement="Bottom" x:Name="Popup" Focusable="False" StaysOpen="False" AllowsTransparency="True"  Margin="0,1,0,0">
                            <Grid x:Name="dd" SnapsToDevicePixels="True">
                                <Border x:Name="ddb" Margin="0,-1,0,0" BorderBrush="DarkGray"  BorderThickness="1" CornerRadius="0,0,3,3" Background="Gray">
                                    <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition />
                                        <RowDefinition />
                                        <RowDefinition />
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition />
                                        <ColumnDefinition />
                                    </Grid.ColumnDefinitions>
                                    <TextBlock Text="Uno:" Grid.Row="0" Grid.Column="0" />
                                    <TextBox Text="{Binding Path=calendar.uno, Mode=TwoWay, StringFormat={}{0:0.##}}" Grid.Row="0" Grid.Column="1" />
                                    <TextBlock Text="Due:" Grid.Row="1" Grid.Column="0" />
                                        <TextBox Text="{Binding Path=calendar.due, Mode=TwoWay, StringFormat={}{0:0.##}}" Grid.Row="1" Grid.Column="1" />
                                    <TextBlock Text="Tre:" Grid.Row="2" Grid.Column="0" />
                                        <TextBox Text="{Binding Path=calendar.tre, Mode=TwoWay, StringFormat={}{0:0.##}}" Grid.Row="2" Grid.Column="1" />
                                    </Grid>
                                </Border>
                            </Grid>
                        </Popup>
                    </Grid>
                </DataTemplate>
            </DataGridTemplateColumn.CellEditingTemplate>

Всплывающее окно работает, но часто возникает следующее исключение:

System.ArgumentNullException was unhandled
  Message=Value cannot be null.
Parameter name: descendant
  Source=PresentationCore
  ParamName=descendant
  StackTrace:
       at System.Windows.Media.VisualTreeHelper.IsAncestorOf(DependencyObject ancestor, DependencyObject descendant, Type stopType)
       at System.Windows.Controls.DataGridCell.RemoveBindingExpressions(BindingGroup bindingGroup, DependencyObject element)
       at System.Windows.Controls.DataGridCell.BuildVisualTree()
       at System.Windows.Controls.DataGridCell.OnIsEditingChanged(Boolean isEditing)
       at System.Windows.Controls.DataGridCell.OnIsEditingChanged(Object sender, 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, Boolean value)
       at System.Windows.Controls.DataGridCell.BeginEdit(RoutedEventArgs e)
       at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(ExecutedRoutedEventArgs e)
       at System.Windows.Controls.DataGrid.OnExecutedBeginEdit(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.BeginEdit(RoutedEventArgs editingEventArgs)
       at System.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDown(MouseButtonEventArgs e)
       at System.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDownThunk(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.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
       at System.Windows.UIElement.OnMouseDownThunk(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)
       at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
       at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
       at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
       at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
       at System.Windows.Threading.Dispatcher.Run()
       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 WpfApplication5.App.Main() in C:\Users\r.sarati\Desktop\WpfDataGridSynchronized_V1.00\WpfDataGridSynchronized\CF40\WpfApplication5\obj\Debug\App.g.cs:line 50
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

В чем проблема?(использование нескольких столбцов не является допустимой альтернативой)

1 Ответ

1 голос
/ 08 августа 2012

в настоящее время у меня тоже есть это исключение в моем приложении;та же трассировка стека.Я нашел также несколько решений для этого, но эти решения не очень «хороши»:

1 Я использовал стиль аэро для всего диалога, где у меня есть DataGrid, чтобы иметь одинаковый вид для элементов управления по умолчанию в разныхВерсии Windows (в основном для XP, чтобы элементы управления выглядели «приятнее»).Когда я комментирую следующую часть кода в xaml диалогового окна, никакие другие исключения не отображаются:

<ResourceDictionary.MergedDictionaries>
       <ResourceDictionary Source="/PresentationFramework.Aero, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=MSIL;component/themes/aero.normalcolor.xaml" />
</ResourceDictionary.MergedDictionaries>

Но я сейчас на XP, я должен проверить, решена ли эта проблема также на Win7.РЕДАКТИРОВАТЬ: работает также для Windows 7.

2 Попробуйте проверить эту ссылку на странице Microsoft: http://support.microsoft.com/kb/2498911

3 Как написано также наНа странице Microsoft вы по-прежнему можете отключить виртуализацию для строки или столбца вашей таблицы данных, но если у вас есть, например, 1000 строк, загрузка всего занимает некоторое время: /

РЕДАКТИРОВАТЬ:

4. Я скачал Aero.NormalColor.xaml (часть тем от Microsoft, доступную здесь: http://msdn.microsoft.com/en-us/library/aa970773.aspx) и добавил эту тему в мой app.xaml в словарь приложения. Похоже, этоисправил проблему (возможно, тот же внешний вид, но есть некоторые различия в коде для этой темы).

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Themes/GlassButton.xaml"/>
            <ResourceDictionary Source="Themes/Aero.NormalColor.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...