【发布时间】:2018-07-17 09:59:49
【问题描述】:
所以我正在开发从数据库中检索数据的应用程序,我想用我创建的自定义列在 DataGrid 中显示它。
XAML:
<DataGrid x: Name = "dataGridAddedAgents" Grid.Column = "0" Grid.ColumnSpan = "7" ItemsSource = "{Binding}" HorizontalAlignment = "Stretch" Margin = "10,0" Grid.Row = "3" VerticalAlignment = "Top" AutoGenerateColumns = "False" IsReadOnly = "True" >
<DataGrid.Columns>
<DataGridTextColumn Binding = "{Binding Path=Id}" Width = "0.25*" Header = "Id" CanUserResize = "False" CanUserReorder = "False" Foreground = "{x:Null}" />
<DataGridTextColumn Binding = "{Binding Path=FirstName}" Width = "0.15*" Header = "First name" CanUserResize = "False" CanUserReorder = "False" Foreground = "{x:Null}" />
<DataGridTextColumn Binding = "{Binding Path=LastName}" Width = "0.15*" Header = "Last name" CanUserResize = "False" CanUserReorder = "False" Foreground = "{x:Null}" />
<DataGridTextColumn Binding = "{Binding Path=Email}" Width = "0.20*" Header = "Email" CanUserResize = "False" CanUserReorder = "False" Foreground = "{x:Null}" />
<DataGridTextColumn Binding = "{Binding Path=Username}" Width = "0.15*" Header = "Username" CanUserResize = "False" CanUserReorder = "False" Foreground = "{x:Null}" />
<DataGridTextColumn Width = "0.10*" ClipboardContentBinding = "{x:Null}" Header = "Remove" CanUserResize = "False" CanUserReorder = "False" Foreground = "{x:Null}" />
</DataGrid.Columns>
</DataGrid>
这是我尝试将数据放入 DataGrid 的 C# 代码
response = await client.GetAsync("api/user/agents");
listOfAgents = await response.Content.ReadAsAsync<ICollection<ApplicationUserModel>>();
dataGridAddedAgents.ItemsSource = listOfAgents;
我已检查调试器并将数据正确加载到 listOfAgents 中。当我运行程序 DataGrid 显示正确的行数但所有单元格都是空的。
编辑:
public class ApplicationUserModel
{
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string GuestIdentification { get; set; }
public string Email { get; set; }
public string Username { get; set; }
public string Password { get; set; }
}
类 ApplicationUserModel 看起来像这样。我也用它写入数据库,它可以工作 苏鲁廷:
从 DataGrid 中的列中删除 Foreground = "{x:Null}" 修复了它。感谢@mm8 的帮助
【问题讨论】:
-
您在代码中以及通过 XAML 中的
ItemsSource = "{Binding}"分配 ItemsSource。这可能是问题的原因。删除绑定,看看它是否有效。 -
或者只是在 xaml 中正确设置 ItemsSource 绑定
-
@TheLethalCoder - 我确实想过建议这样做,但可能还有其他问题需要排序。删除绑定(即使是暂时的)将显示它是否是问题的根源。一旦你确定你可以找到一个合适的解决方案。
-
你可以检查输出窗口是否有绑定错误
-
@ChrisF 当我在 XAML 中删除 ItemsSource 相同的东西时。当我把 AutoGenerateColumns 数据显示没有问题。但我不能使用那个因为我没有显示我得到的所有东西。问题出在将列绑定到特定数据中
标签: c# wpf data-binding