c# - WPF Datagrid 在 header 排序时崩溃

标签 c# wpf binding datagrid

此问题与 What is it about DataTable Column Names with dots that makes them unsuitable for WPF's DataGrid control? 相关.

我使用数据网格来显示临时查询生成器的结果,因此数据表列可以是任何内容。

我关注了得票最多的答案(14)。一切都很好,但如果我单击标题对列进行排序,整个应用程序就会崩溃。

错误:

System.IndexOutOfRangeException   HResult=0x80131508   Message=Index was outside the bounds of the array.   Source=AppName   StackTrace:    at AppName.App.ShowUnhandeledException(DispatcherUnhandledExceptionEventArgs e) in <path>\App.xaml.cs:line 51    at AppName.App.AppDispatcherUnhandledException(Object sender, DispatcherUnhandledExceptionEventArgs e) in <path>\App.xaml.cs:line 27 at System.Windows.Threading.Dispatcher.CatchException(Exception e)    at System.Windows.Threading.Dispatcher.CatchExceptionStatic(Object source, Exception e)    at System.Windows.Threading.ExceptionWrapper.CatchException(Object source, Exception e, Delegate catchHandler)    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 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.Application.RunDispatcher(Object ignore)    at System.Windows.Application.RunInternal(Window window)    at System.Windows.Application.Run(Window window)    at System.Windows.Application.Run()    at AppName.App.Main()

这是我的 XAML:

<DataGrid x:Name="DgridQueryResults" Grid.Row="1" Background="LightGray" Margin="5" ItemsSource ="{Binding .}" IsReadOnly="True" CanUserAddRows="False" CanUserDeleteRows="False" CanUserResizeColumns="true" CanUserReorderColumns="False" CanUserSortColumns="True" ClipboardCopyMode="ExcludeHeader"SelectionUnit="Cell" CopyingRowClipboardContent="DgridQueryResults_CopyingRowClipboardContent" Grid.ColumnSpan="2"/>                             

我尝试了上面的项目源,例如 ItemsSource ="{Binding}" 但它仍然崩溃。

我以编程方式添加括号,如下所示:

        private void DgridQueryResults_ColumnSetup()
    {
        DgridQueryResults.Columns.Clear();
        DgridQueryResults.AutoGenerateColumns = false;
        foreach (DataColumn column in _results.Columns)
        {
            var gridColumn = new DataGridTextColumn()
            {
                Header = column.ColumnName,
                Binding = new Binding("[" + column.ColumnName + "]")
            };

            DgridQueryResults.Columns.Add(gridColumn);
        }
    }

我在设置项目源之前设置列,如下所示:

        private void ExecuteSql()
    {
        if (_dataFormData.GetDataViaReader(_sql))
        {
            _results = _dataFormData.DT;
            DgridQueryResults_ColumnSetup();// <-- column setup
            DgridQueryResults.DataContext = _results.DefaultView;

        }
        else
        {
            DgridQueryResults.DataContext = null;
        }

        QueryResults.Focus();
    }

注释掉列设置工作正常,但是我不能使用违反绑定(bind)的列名称(即句号 (.))。

此外,在 XAML 中将用户排序设置为 false 可以修复该问题,但用户当然无法对数据进行排序。

我正在针对 Framework 4.6.1 使用 VS 2017 15.5.1。

还有其他人遇到过这种情况吗?我很感激任何帮助。谢谢!

最佳答案

我明白了。添加列时我必须添加排序成员路径。

private void DgridQueryResults_ColumnSetup()
{
    DgridQueryResults.Columns.Clear();
    DgridQueryResults.AutoGenerateColumns = false;
    foreach (DataColumn column in _results.Columns)
    {
        var gridColumn = new DataGridTextColumn()
        {
            Header = column.ColumnName,
            SortMemberPath = column.ColumnName, //<--added
            Binding = new Binding("[" + column.ColumnName + "]")
        };


        DgridQueryResults.Columns.Add(gridColumn);
    }
}

关于c# - WPF Datagrid 在 header 排序时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47797269/

相关文章:

wpf - 是 x :Array supported on Windows Phone 7

.net - 如何在 WPF MVVM 中使用用户控件

xaml - 如何在 XAML 中绑定(bind) listview 的项目数

C++:在 DLL 中绑定(bind)类函数

c# - 处理任务异常——自定义TaskScheduler

C# 谷歌驱动器 : Allow users read access to my drive

c# - 在 SET 子句中多次指定列名 'phoneNumber'

c# - Winforms - 如何改变 ListView 控件中行的颜色?

c# - 按名称属性比较文本框控件

c# - 使用 GridSplitter 调整网格大小