C# WPF 工具包:如何​​使数据网格中的单元格可编辑?

发布于 2024-07-30 07:55:24 字数 9106 浏览 1 评论 0原文

请记下这个使用 Microsoft Visual Studio 2008 编写的小型 WPF C# 程序的代码:

.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("");
        }
    }
}

该程序仅显示一个 WPF 工具包数据网格,其中包含 10 列,其中包含标题和一个空行。

当选中空行的某个单元格然后单击进行编辑时会出现问题:程序崩溃。 Visual Studio 中会显示一个消息框,内容如下:“当前位置没有可用的源代码。” 我想知道如何使数据网格中的单元格可编辑?


这是异常和堆栈跟踪:

System.InvalidOperationException 是 unhandled Message="'EditItem' 不是 允许此视图。”
来源=“演示框架”
堆栈跟踪: 在 System.Windows.Controls.ItemCollection.System.ComponentModel.IEditableCollectionView.EditItem(对象 物品) 在 Microsoft.Windows.Controls.DataGrid.EditRowItem(对象 行项)中 C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGrid.cs:line 3396 在 Microsoft.Windows.Controls.DataGrid.OnExecutedBeginEdit(ExecutedRoulatedEventArgs e) 在 C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGrid.cs:line 2208 在 Microsoft.Windows.Controls.DataGrid.OnExecutedBeginEdit(对象 发送者、ExecutedRoatedEventArgs e) 中 C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGrid.cs:line 2036 在 System.Windows.Input.CommandBinding.OnExecuted(对象 发送者、执行路由事件参数 e) 在 System.Windows.Input.CommandManager.ExecuteCommandBinding(对象 发送者,ExecutedRoatedEventArgs e, 命令绑定(命令绑定) 在 System.Windows.Input.CommandManager.FindCommandBinding(CommandBindingCollection commandBindings,对象发送者, RoutedEventArgs e,ICommand 命令, 布尔执行) 在 System.Windows.Input.CommandManager.FindCommandBinding(对象 发送者、RoatedEventArgs e、ICommand 命令,布尔执行) 在 System.Windows.Input.CommandManager.OnExecuted(对象 发送者、执行路由事件参数 e) 在 System.Windows.UIElement.OnExecutedThunk(对象 发送者、执行路由事件参数 e) 在 System.Windows.Input.ExecutedRoulatedEventArgs.InvokeEventHandler(委托 genericHandler,对象目标) 在 System.Windows.RoatedEventArgs.InvokeHandler(委托 处理程序,对象目标) 在 System.Windows.RoatedEventHandlerInfo.InvokeHandler(对象 目标、RoatedEventArgs 路由事件参数) 在 System.Windows.EventRoute.InvokeHandlersImpl(对象 源、RoatedEventArgs 参数、布尔值 重新加注) 在 System.Windows.UIElement.RaiseEventImpl(DependencyObject 发送者、RoatedEventArgs 参数) 在 System.Windows.UIElement.RaiseEvent(RoatedEventArgs args,布尔值可信) 在 System.Windows.Input.RoatedCommand.ExecuteImpl(对象 参数,IInputElement 目标, 布尔值 userInitiated) 在 System.Windows.Input.RoatedCommand.Execute(对象 参数,IInputElement 目标) 在 Microsoft.Windows.Controls.DataGrid.BeginEdit(RoulatedEventArgs 编辑事件参数)中 C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGrid.cs:line 3059 在 Microsoft.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDown(MouseButtonEventArgs e) 在 C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGridCell.cs:line 第748章 在 Microsoft.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDownThunk(对象 发送者、MouseButtonEventArgs e) 中 C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGridCell.cs:line 第726章 在 System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(委托 genericHandler、对象 genericTarget) 在 System.Windows.RoatedEventArgs.InvokeHandler(委托 处理程序,对象目标) 在 System.Windows.RoatedEventHandlerInfo.InvokeHandler(对象 目标、RoatedEventArgs 路由事件参数) 在 System.Windows.EventRoute.InvokeHandlersImpl(对象 源、RoatedEventArgs 参数、布尔值 重新加注) 在 System.Windows.UIElement.ReRaiseEventAs(DependencyObject 发送者,RoatedEventArgs 参数, 路由事件(新事件) 在 System.Windows.UIElement.CrackMouseButtonEventAndReRaiseEvent(DependencyObject 发送者、MouseButtonEventArgs e) 在 System.Windows.UIElement.OnMouseDownThunk(对象 发送者、MouseButtonEventArgs e) 在 System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(委托 genericHandler、对象 genericTarget) 在 System.Windows.RoatedEventArgs.InvokeHandler(委托 处理程序,对象目标) 在 System.Windows.RoatedEventHandlerInfo.InvokeHandler(对象 目标、RoatedEventArgs 路由事件参数) 在 System.Windows.EventRoute.InvokeHandlersImpl(对象 源、RoatedEventArgs 参数、布尔值 重新加注) 在 System.Windows.UIElement.RaiseEventImpl(DependencyObject 发送者、RoatedEventArgs 参数) 在 System.Windows.UIElement.RaiseEvent(RoatedEventArgs args,布尔值可信) 在 System.Windows.Input.InputManager.ProcessStagingArea() 在 System.Windows.Input.InputManager.ProcessInput(InputEventArgs 输入) 在 System.Windows.Input.InputProviderSite.ReportInput(InputReport 输入报告) 在 System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd、InputMode 模式、Int32 时间戳、 RawMouseActions 操作,Int32 x, Int32 y、Int32 轮) 在 System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd、Int32 消息、IntPtr wParam、IntPtr lParam、布尔值& 已处理) 在 System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd、Int32 消息、IntPtr wParam、IntPtr lParam、布尔值& 已处理) 在 MS.Win32.HwndWrapper.WndProc(IntPtr hwnd、Int32 消息、IntPtr wParam、IntPtr lParam、布尔值& 已处理) 在 MS.Win32.HwndSubclass.DispatcherCallbackOperation(对象 Ø) 在 System.Windows.Threading.ExceptionWrapper.InternalRealCall(委托 回调、对象参数、布尔值 是单个参数) 在 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(对象 源、委托回调、对象 args,布尔值 isSingleParameter, 委托catchHandler) 在 System.Windows.Threading.Dispatcher.WrappedInvoke (委托 回调、对象参数、布尔值 isSingleParameter,委托 捕获处理程序) 在 System.Windows.Threading.Dispatcher.InvokeImpl (DispatcherPriority 优先级、TimeSpan 超时、委托 方法、对象参数、布尔值 是单个参数) 在 System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority 优先级、委托方法、对象参数) 在 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd、Int32 msg、IntPtr wParam、IntPtr l参数) 在 MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& 味精) 在 System.Windows.Threading.Dispatcher.PushFrameImpl (DispatcherFrame 框架) 在 System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame 框架) 在 System.Windows.Threading.Dispatcher.Run() 在 System.Windows.Application.RunDispatcher(对象 忽略) 在 System.Windows.Application.RunInternal(窗口 窗户) 在 System.Windows.Application.Run(窗口 窗户) 在 System.Windows.Application.Run() 在 WpfDatagridTest.App.Main() 中 C:\Users\Frank\Documents\Visual_Studio_2008\Projects\WpfDatagridTest\WpfDatagridTest\obj\Debug\App.g.cs:line 0 在 System.AppDomain._nExecuteAssembly(程序集 程序集,String[] args) 在 System.AppDomain.ExecuteAssembly(字符串 汇编文件、证据 assemblySecurity,String[] args) 在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() 在 System.Threading.ThreadHelper.ThreadStart_Context(对象 状态) 在 System.Threading.ExecutionContext.Run(ExecutionContext 执行上下文、上下文回调 回调,对象状态) 在 System.Threading.ThreadHelper.ThreadStart() 内部异常:

Take note of the code for this small WPF C# program made with 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("");
        }
    }
}

This program simply shows a WPF toolkit datagrid with 10 columns with headers and an empty row.

There is problem that occurs when a certain cell of the empty row is selected and then clicked to be edited: the program crashes. A message box shows up in Visual Studio saying this: "There is no source code available for the current location." I would like to know how can I make a cell from a datagrid be editable?


Here is the exception and stacktrace:

System.InvalidOperationException was
unhandled Message="'EditItem' is not
allowed for this view."
Source="PresentationFramework"
StackTrace:
at System.Windows.Controls.ItemCollection.System.ComponentModel.IEditableCollectionView.EditItem(Object
item)
at Microsoft.Windows.Controls.DataGrid.EditRowItem(Object
rowItem) in
C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGrid.cs:line
3396
at Microsoft.Windows.Controls.DataGrid.OnExecutedBeginEdit(ExecutedRoutedEventArgs
e) in
C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGrid.cs:line
2208
at Microsoft.Windows.Controls.DataGrid.OnExecutedBeginEdit(Object
sender, ExecutedRoutedEventArgs e) in
C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGrid.cs:line
2036
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 Microsoft.Windows.Controls.DataGrid.BeginEdit(RoutedEventArgs
editingEventArgs) in
C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGrid.cs:line
3059
at Microsoft.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDown(MouseButtonEventArgs
e) in
C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGridCell.cs:line
748
at Microsoft.Windows.Controls.DataGridCell.OnAnyMouseLeftButtonDownThunk(Object
sender, MouseButtonEventArgs e) in
C:\dd\WPF_1\src\wpf\src\ControlsPack\WPFToolkit\DataGrid\Microsoft\Windows\Controls\DataGridCell.cs:line
726
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.CrackMouseButtonEventAndReRaiseEvent(DependencyObject
sender, MouseButtonEventArgs e)
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.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, Int32 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, Boolean
isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object
source, Delegate callback, Object
args, Boolean isSingleParameter,
Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate
callback, Object args, Boolean
isSingleParameter, Delegate
catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority
priority, TimeSpan timeout, Delegate
method, Object args, Boolean
isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority
priority, Delegate method, Object arg)
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 WpfDatagridTest.App.Main() in
C:\Users\Frank\Documents\Visual_Studio_2008\Projects\WpfDatagridTest\WpfDatagridTest\obj\Debug\App.g.cs:line
0
at System.AppDomain._nExecuteAssembly(Assembly
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)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

如梦 2024-08-06 07:55:24

您将 ItemsSource 设置为 Binding,但没有 DataContext,因此此绑定毫无用处。 然后,您在代码隐藏中生成列并用临时数据填充它们。 根据我对 DataGrid 的了解,仅当存在网格绑定的数据时才支持编辑。 否则,您正在编辑什么数据?

此外,我相信有一个 IsReadOnly 属性(检查 DataGrid 文档),需要将其设置为 false (但我认为默认情况下它是 false)。

You are setting your ItemsSource to Binding, but there is no DataContext so this binding is useless. Then you are generating the columns in the code-behind and filling them with temporary data. From what I understand about the DataGrid, editing is only supported if there is data that the grid is bound to. Otherwise, what data are you editing?

Furthermore, I believe there is a IsReadOnly property (check the DataGrid documentation), which needs to be set to false (but I think it is false by default).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文