【问题标题】:DataGrid is not show the data instead its show Model Class NameDataGrid 不显示数据,而是显示模型类名称
【发布时间】:2016-12-03 16:33:19
【问题描述】:

当我将数据集合绑定到我的数据网格时,它不显示数据而不是数据,它显示模型类名称我有多少行有那么多时间。我尝试了普通的 WPF 数据网格和 Dev Express 数据网格,但对我来说没有任何效果。

XAML:

使用 WPF 数据网格

 <DataGrid ItemsSource="{Binding EmpDetails}" AutoGenerateColumns="True"/>

使用 Dev Express DataGrid

 <dxg:GridControl ItemsSource="{Binding EmpDetails}" AutoPopulateColumns="True" AutoGenerateColumns="AddNew" >
                            <dxg:GridControl.View>
                                <dxg:TableView />
                            </dxg:GridControl.View>
                        </dxg:GridControl>

我的收藏中有 2 条记录,请在下面找到图片

https://i.stack.imgur.com/pdjQt.jpg

Dev Express DataGrid 运行时图片:

https://i.stack.imgur.com/Iq9VC.jpg

WPF DataGrid 运行时图片:

https://i.stack.imgur.com/HMgd8.png

感谢您花时间回答我的问题。

【问题讨论】:

  • 你能 1. 发布你的 EmployeeDetails 类的代码和 2. 添加显示的数据网格的图像
  • EmployeeDetails 仅适用于模型类。它有一些属性。表格的每一列都有模型类的每个属性

标签: c# wpf wpfdatagrid


【解决方案1】:

确保从“EmpDetails”源属性返回的 IEnumerable 中的类型 T 对于您希望在 DataGrid 中自动生成的每一列都有一个 公共属性(不是字段) .请参考以下示例代码。

型号:

Public Class EmployeeDetails
  Public Property ColumnA As String
  Public Property ColumnB As String
End Class

查看模型:

Public Class ViewModel
Public Sub New()
    EmpDetails = New List(Of EmployeeDetails)
    EmpDetails.Add(New EmployeeDetails With {.ColumnA = "A1", .ColumnB = "B1"})
    EmpDetails.Add(New EmployeeDetails With {.ColumnA = "A2", .ColumnB = "B2"})
End Sub

Public Property EmpDetails As ObservableCollection(Of EmployeeDetails)

End Class

查看:

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication1"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
    <local:ViewModel />
</Window.DataContext>
<Grid>
    <DataGrid ItemsSource="{Binding EmpDetails}" AutoGenerateColumns="True"/>
</Grid>

MainWindow

【讨论】:

  • 没有 mm8,我的收藏不是 IEnumerable。它是一个 EmployeeDetails 类。你能看到我的第一张图片吗
  • An ObservableCollection 是一个 IEnumerable (ObservableCollection 类实现了 IEnumerable 接口)...所以你应该确保你的 EmployeeDetails 每个都有一个公共属性您希望在 DataGrid 中自动生成的列。
  • 是的,所有都是公共属性
  • 显然不是...请参考我提供的示例代码。如图所示,它显然可以正常工作。您应该将您的代码与此进行比较。如果您需要任何进一步的帮助,还请发布您的 EmployeeDetails 类的实现。
【解决方案2】:

将 EmployeeDetails 放在 Observable 集合中,并且表的所有列都写为具有 OnPropertyChange 的属性,包括模型类。

前:

private string firstName;
public string FirstName
{
 get {return firstName;}
 set { firstName = value; OnPropertyChange("FirstName");}
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 2020-06-10
    • 1970-01-01
    • 2021-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多