【发布时间】:2017-09-19 15:14:52
【问题描述】:
这是运行的方法,它在程序启动时触发,当单击按钮刷新列表时(它从 SQL 服务器数据库中提取其信息,其他运行时间日志程序的人可以添加时间这只是所有时间日志的主列表)
private void viewPeopleTimLog()
{
string message;
//Datagrid cleared out
dtgPeopleTimLog.ItemsSource = null;
//List of TimeLog Objects.
//It passes back out a blank string if nothing goes wrong and passes
//back out the out the error message if something goes wrong
PeopleTimeLogList logList = new PeopleTimeLogList(out message);
if(string.IsNullOrEmpty(message)) //Everything is fine
{
dtgPeopleTimLog.ItemsSource = logList; //Line it fails on
}
else
{
//Code to print the exception message here
}
}
TimeLog 对象包含 1. 人的 id # 存储为 int。 2. 以字符串形式存储的人名。 3. 该人对已完成工作的评论以字符串形式存储。 4. 记录时间的日期存储为 DateTime。 5. 该人记录的时间量存储为 double。
这是数据网格的 xaml 代码
<DataGrid x:Name="dtgPeopleTimLog" HorizontalAlignment="Left"
Margin="10,45,0,0" VerticalAlignment="Top" Height="404"
Width="1000" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Date Logged" Binding="{Binding DateLogged}"/>
<DataGridTextColumn Header="ID #" Binding="{Binding IDNumber}"/>
<DataGridTextColumn Header="Name" Binding="{Binding PersonName}"/>
<DataGridTextColumn Header="Time Logged" Binding="{Binding TimeLogged}"/>
<DataGridTextColumn Header="Comment" Binding="{Binding Comment}">
<DataGridTextColumn.ElementStyle>
<Style>
<Setter Property="TextBlock.TextWrapping" Value="Wrap" />
<Setter Property="TextBlock.Width" Value="540"/>
</Style>
</DataGridTextColumn.ElementStyle>
</DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
我在这里遗漏了什么吗?我看了又看,似乎没有什么与我的情况相匹配。我将所有列从对象绑定到数据网格,并且在获取 TimeLog 对象列表并将其放置为 itemssource 之前,我正在清除 itemssource。感谢任何帮助!
【问题讨论】:
-
尝试在
dtgPeopleTimLog.ItemsSource = logList;上设置断点并在调试器中检查dtgPeopleTimLog.Items属性的内容。不应该有任何项目 -
当您在
<DataGrid>标记中放入不是DataGrid 属性的任何内容(如DataGrid.Columns)并因此被隐式处理为一个项目时,您可能会遇到此异常。您在此处显示的内容是您的实际 XAML 吗? -
是的,它是@Clemens。而且我之前用另一个程序完成了确切的代码(不同的对象,但相同的想法),它没有引起任何问题
-
@ASh 我这样做了,但没有任何项目
-
请注意,这个派生的集合类构造函数看起来很奇怪。为什么不直接抛出并捕获异常而不是返回错误消息作为输出参数?但如果这样做,则应始终将新创建的集合分配给 ItemsSource 属性。如果出现错误,它将为空。无需提前将 ItemsSource 设置为 null。