所以我正在处理从数据库中检索数据的应用程序,我想在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>
这里是c#代码,我尝试将数据放入DataGrid
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看起来像这样。我也使用它写入数据库,它的工作原理 Soulutin:
删除Foreground =&#34; {x:Null}&#34;从DataGrid中的列修复它。感谢@ mm8的帮助
答案 0 :(得分:2)
当我运行程序时,DataGrid显示正确的行数,但所有单元格都是空的。
然后,您需要确保ApplicationUserModel类包含名为&#34; Id&#34;,&#34; FirstName&#34;,&#34的公共属性(而非字段) ; LastName&#34;,&#34; Email&#34;和&#34;用户名&#34;并且这些属性通常会返回预期值。
每个属性至少应该有一个公共setter,以便您能够绑定它们:
public class ApplicationUserModel
{
public string Id {get; set; }
public string FirstName {get; set; }
...
}
修改:你还要删除Foreground =&#34; {x:Null}&#34;来自您的DataGridTextColumns。
顺便说一句,你以编程方式设置的ItemsSource将覆盖&#34;你在XAML标记中绑定的那个。
答案 1 :(得分:0)
显然,我的变量没有设置为public,现在可以使用了。