这是我见过的最奇怪的错误!拔我的头发!
我有一个带有 DataGrid 的窗口,它绑定到具有自动生成列的通用 List[object]。
在内部,我们有 2 个不同的 PC 版本。在一种类型上,窗口(正确)显示如下:
这是在其他 PC 构建类型上(不正确):
这两种类型的 PC 都是 Win 7 x64 版本,但主要区别在于显卡。在这两种情况下,我都运行完全相同的二进制文件和配置。
我的窗口的代码在这里:
<Window x:Class="FicClient.Server.ComponentWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:System="clr-namespace:System;assembly=mscorlib" Title="{Binding RelativeSource={RelativeSource AncestorType=ContentControl, AncestorLevel=1}, Path=Section}" Height="418" Width="525" Loaded="Window_Loaded" Icon="/FicClient;component/images/Visualpharm-Must-Have-Information.ico">
<DockPanel>
<DockPanel DockPanel.Dock="Top" HorizontalAlignment="Stretch" Margin="4" Background="Azure">
<TextBlock DockPanel.Dock="Left" VerticalAlignment="Center">Note: Component data is a snapshot and does not update</TextBlock>
<Button DockPanel.Dock="Right" HorizontalAlignment="Right" Click="Button_Click">
<StackPanel Orientation="Horizontal">
<Image Source="/FicClient;component/images/excel.ico" Stretch="Uniform" Height="25" />
<TextBlock VerticalAlignment="Center" Padding="5,0">Copy</TextBlock>
</StackPanel>
</Button>
</DockPanel>
<DataGrid Name="DataGridComponents" ClipboardCopyMode="IncludeHeader" ItemsSource="{Binding Mode=OneTime}" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" IsReadOnly="True" >
</DataGrid>
</DockPanel>
</Window>
出于调试目的,当窗口打开时,它还会显示一个弹出窗口,告诉我列表中有多少项目,并且在这两种情况下,该数字都是相同且正确的。然而,在一种 PC 类型上,它只是 FUBAR。
有没有人遇到过这种问题?我还能做些什么来调试它吗?
** 使用选定的答案更新 **
问题确实是在安装了 4.0 和 4.5 的机器上与仅安装了 4.0 的机器上的行为似乎不同,即使应用程序是针对 4.0 编译的
我的解决方案是手动生成列。我所做的是将事件处理程序绑定到 DataGrid 上的 DataContextChanged,然后在处理程序中执行以下操作:
private void DataGridComponents_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
var dataGrid = sender as DataGrid;
if (dataGrid == null) return;
var rows = dataGrid.DataContext as List<object>;
if (rows == null) return;
if (rows.Count == 0) return;
var first = rows[0];
foreach (var property in first.GetType().GetProperties())
{
var column = new DataGridTextColumn
{
Header = property.Name,
Binding = new Binding(property.Name)
};
column.Binding.StringFormat = "{0:0.00}";
dataGrid.Columns.Add(column);
}
}