Kit de herramientas C # WPF: ¿Cómo puedo hacer que una celda de una cuadrícula de datos sea editable?
-
22-07-2019 - |
Pregunta
Tome nota del código para este pequeño programa WPF C # hecho con Microsoft Visual Studio 2008:
.xaml
<Window x:Class="WpfDatagridTest.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:WpfToolkit="http://schemas.microsoft.com/wpf/2008/toolkit"
Title="Window1" Height="300" Width="300">
<Grid>
<WpfToolkit:DataGrid
x:Name="DataGrid_" ItemsSource="{Binding}"
SelectionMode="Extended"
CanUserAddRows="False" CanUserDeleteRows="False"
CanUserResizeRows="False" CanUserSortColumns="False"
AutoGenerateColumns="False"
RowHeaderWidth="17" RowHeight="25" />
</Grid>
</Window>
.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls;
namespace WpfDatagridTest
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
const int MAX = 10;
for(int i = 0; i < MAX; ++i)
DataGrid_.Columns.Add(new DataGridTextColumn()
{
Header = i
});
DataGrid_.Items.Add("");
}
}
}
Este programa simplemente muestra una cuadrícula de datos del kit de herramientas WPF con 10 columnas con encabezados y una fila vacía.
Hay un problema que ocurre cuando se selecciona una celda determinada de la fila vacía y luego se hace clic para editarla: el programa se bloquea. Aparece un cuadro de mensaje en Visual Studio que dice esto: "No hay ningún código fuente disponible para la ubicación actual". Me gustaría saber cómo puedo hacer que una celda de una cuadrícula de datos sea editable.
Aquí está la excepción y stacktrace:
System.InvalidOperationException era Mensaje no manejado = " 'EditItem' no es permitido para esta vista. "
Fuente = " PresentationFramework "
StackTrace: en System.Windows.Controls.ItemCollection.System.ComponentModel.IEditableCollectionView.EditItem (Object ít) en Microsoft.Windows.Controls.DataGrid.EditRowItem (Object rowItem) en C: \ dd \ WPF_1 \ src \ wpf \ src \ ControlsPack \ WPFToolkit \ DataGrid \ Microsoft \ Windows \ Controls \ DataGrid.cs: línea 3396 en Microsoft.Windows.Controls.DataGrid.OnExecutedBeginEdit (ExecutedRoutedEventArgs e) en C: \ dd \ WPF_1 \ src \ wpf \ src \ ControlsPack \ WPFToolkit \ DataGrid \ Microsoft \ Windows \ Controls \ DataGrid.cs: línea 2208 en Microsoft.Windows.Controls.DataGrid.OnExecutedBeginEdit (Object remitente, ExecutedRoutedEventArgs e) en C: \ dd \ WPF_1 \ src \ wpf \ src \ ControlsPack \ WPFToolkit \ DataGrid \ Microsoft \ Windows \ Controls \ DataGrid.cs: línea 2036 en System.Windows.Input.CommandBinding.OnExecuted (Object remitente, ExecutedRoutedEventArgs e) en System.Windows.Input.CommandManager.ExecuteCommandBinding (Object remitente, ExecutedRoutedEventArgs e, CommandBinding commandBinding) en System.Windows.Input.CommandManager.FindCommandBinding (CommandBindingCollection commandBindings, Object remitente, RoutedEventArgs e, comando ICommand, Ejecución booleana) en System.Windows.Input.CommandManager.FindCommandBinding (Object remitente, RoutedEventArgs e, ICommand comando, ejecución booleana) en System.Windows.Input.CommandManager.OnExecuted (Object remitente, ExecutedRoutedEventArgs e) en System.Windows.UIElement.OnExecutedThunk (Object remitente, ExecutedRoutedEventArgs e) en System.Windows.Input.ExecutedRoutedEventArgs.InvokeEventHandler (Delegado genericHandler, Objetivo del objeto) en System.Windows.RoutedEventArgs.InvokeHandler (Delegado controlador, objetivo de objeto) en System.Windows.RoutedEventHandlerInfo.InvokeHandler (Object target, RoutedEventArgs routedEventArgs) en System.Windows.EventRoute.InvokeHandlersImpl (Object fuente, arcos RoutedEventArgs, booleano resucitado) en System.Windows.UIElement.RaiseEventImpl (DependencyObject remitente, args RoutedEventArgs) en System.Windows.UIElement.RaiseEvent (RoutedEventArgs args, booleano de confianza) en System.Windows.Input.RoutedCommand.ExecuteImpl (Object parámetro, objetivo IInputElement, Usuario booleano iniciado) en System.Windows.Input.RoutedCommand.Execute (Object parámetro, objetivo IInputElement) en Microsoft.Windows.Controls.DataGrid.BeginEdit (RoutedEventArgs editingEventArgs) en C: \ dd \ WPF_1 \ src \ wpf \ src \ ControlsPack \ WPFToolkit \ DataGrid \ Microsoft \ Windows \ Controls \ DataGrid.cs: línea 3059 en Microsoft.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDown (MouseButtonEventArgs e) en C: \ dd \ WPF_1 \ src \ wpf \ src \ ControlsPack \ WPFToolkit \ DataGrid \ Microsoft \ Windows \ Controls \ DataGridCell.cs: línea 748 en Microsoft.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDownThunk (Object remitente, MouseButtonEventArgs e) en C: \ dd \ WPF_1 \ src \ wpf \ src \ ControlsPack \ WPFToolkit \ DataGrid \ Microsoft \ Windows \ Controls \ DataGridCell.cs: linmi 726 en System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler (Delegado genericHandler, Object genericTarget) en System.Windows.RoutedEventArgs.InvokeHandler (Delegado controlador, objetivo de objeto) en System.Windows.RoutedEventHandlerInfo.InvokeHandler (Object target, RoutedEventArgs routedEventArgs) en System.Windows.EventRoute.InvokeHandlersImpl (Object fuente, arcos RoutedEventArgs, booleano resucitado) en System.Windows.UIElement.ReRaiseEventAs (DependencyObject remitente, RoutedEventArgs args, RoutedEvent newEvent) en System.Windows.UIElement.CrackMouseButtonEventAndReRaiseEvent (DependencyObject remitente, MouseButtonEventArgs e) en System.Windows.UIElement.OnMouseDownThunk (Object remitente, MouseButtonEventArgs e) en System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler (Delegado genericHandler, Object genericTarget) en System.Windows.RoutedEventArgs.InvokeHandler (Delegado controlador, objetivo de objeto) en System.Windows.RoutedEventHandlerInfo.InvokeHandler (Object target, RoutedEventArgs routedEventArgs) en System.Windows.EventRoute.InvokeHandlersImpl (Object fuente, arcos RoutedEventArgs, booleano resucitado) en System.Windows.UIElement.RaiseEventImpl (DependencyObject remitente, args RoutedEventArgs) en System.Windows.UIElement.RaiseEvent (RoutedEventArgs args, booleano de confianza) en System.Windows.Input.InputManager.ProcessStagingArea () en System.Windows.Input.InputManager.ProcessInput (InputEventArgs entrada) en System.Windows.Input.InputProviderSite.ReportInput (InputReport inputReport) en System.Windows.Interop.HwndMouseInputProvider.ReportInput (IntPtr hwnd, modo InputMode, marca de tiempo Int32, Acciones de RawMouseActions, Int32 x, Int32 y, rueda Int32) en System.Windows.Interop.HwndMouseInputProvider.FilterMessage (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, booleano & amp; manejado) en System.Windows.Interop.HwndSource.InputFilterMessage (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, booleano & amp; manejado) en MS.Win32.HwndWrapper.WndProc (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, booleano & amp; manejado) en MS.Win32.HwndSubclass.DispatcherCallbackOperation (Object o) en System.Windows.Threading.ExceptionWrapper.InternalRealCall (Delegado devolución de llamada, argumentos de objeto, booleano isSingleParameter) en System.Windows.Threading.ExceptionWrapper. CalculateCatchWhen (Object fuente, devolución de llamada delegada, objeto args, Boolean isSingleParameter, Delegado catchHandler) en System.Windows.Threading.Dispatcher.WrappedInvoke (Delegado devolución de llamada, argumentos de objeto, booleano isSingleParameter, Delegate catchHandler) en System.Windows.Threading.Dispatcher.InvokeImpl (DispatcherPriority prioridad, TimeSpan timeout, Delegate método, argumentos de objeto, booleano isSingleParameter) en System.Windows.Threading.Dispatcher.Invoke (DispatcherPriority prioridad, método de delegado, objeto arg) en MS.Win32.HwndSubclass.SubclassWndProc (IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam) en MS.Win32.UnsafeNativeMethods.DispatchMessage (MSG & amp; msg) en System.Windows.Threading.Dispatcher.PushFrameImpl (DispatcherFrame marco) en System.Windows.Threading.Dispatcher.PushFrame (DispatcherFrame marco) en System.Windows.Threading.Dispatcher.Run () en System.Windows.Application.RunDispatcher (Object ignorar) en System.Windows.Application.RunInternal (Window ventana) en System.Windows.Application.Run (Window ventana) en System.Windows.Application.Run () en WpfDatagridTest.App.Main () en C: \ Users \ Frank \ Documents \ Visual_Studio_2008 \ Projects \ WpfDatagridTest \ WpfDatagridTest \ obj \ Debug \ App.g.cs: line 0 0 en S
Solución
Está configurando su ItemsSource en Enlace , pero no hay DataContext, por lo que este enlace es inútil. Luego está generando las columnas en el código subyacente y llenándolas con datos temporales. Por lo que entiendo sobre DataGrid, la edición solo es compatible si hay datos a los que está vinculada la cuadrícula. De lo contrario, ¿qué datos está editando?
Además, creo que hay una propiedad IsReadOnly (consulte la documentación de DataGrid), que debe establecerse en falso (pero creo que es falso de forma predeterminada).