DataGrid:ItemsControl与其项目源不一致

时间:2013-10-16 20:15:27

标签: c# .net wpf data-binding datagrid

当我在DataGridViewModel类中调用FillGPLocationAndPrint时,我得到了这个异常。以下是内部异常。会发生什么情况是将硬编码字典传递到FillGPLocationAndPrint,从那里获取数据并将其放入GridData ObservableCollection中,该DataData ObservableCollection绑定到DataGrid的ItemsSource属性。这引发了一个名为CollectionChanged的事件,该事件调用GridDataChanged方法,该方法负责增加DataGrid高度属性和MainWindow高度属性。基本上,当添加和减去行时,网格和窗口高度会动态变化。

修改

在进一步研究这个问题之后,问题实际上是由

引起的
mainVm.WindowHeight += ROW_HEIGHT;

mainVm.WindowHeight -= ROW_HEIGHT;

语句。出于某种原因,它不喜欢改变窗户的高度。 mainVm是一个对象,表示主窗口的ViewModel,WindowHeight是一个绑定到主窗口中Height属性的double。

这是InnerException:

开发人员的信息(使用Text Visualizer阅读本文): 抛出此异常是因为名为“grdData”的控件'System.Windows.Controls.DataGrid Items.Count:3'的生成器已收到与Items集合的当前状态不一致的CollectionChanged事件序列。检测到以下差异:   累计计数2与实际计数3不同。[累计计数为(上一次重置计数+ #Adds - 自上次重置后#Removes)。   在索引1处:Generator的项目“{NewItemPlaceholder}”与实际项目“MechQualTestDataEntry.MechTestData”不同。

以下一个或多个来源可能引发了错误的事件:      System.Windows.Controls.ItemContainerGenerator       System.Windows.Controls.ItemCollection        System.Windows.Data.ListCollectionView         System.Collections.ObjectModel.ObservableCollection`1 [[MechQualTestDataEntry.MechTestData,MechQualTestDataEntry,Version = 2.0.5.25,Culture = neutral,PublicKeyToken = null]] (被认为的主要来源被认为更有可能是问题的原因。)

最常见的原因是(a)在不引发相应事件的情况下更改集合或其计数,以及(b)使用不正确的索引或项目参数引发事件。

异常的堆栈跟踪描述了如何检测到不一致,而不是它们是如何发生的。要获得更及时的异常,请在生成器上将附加属性“PresentationTraceSources.TraceLevel”设置为值“High”并重新运行该方案。一种方法是运行类似于以下的命令:    System.Diagnostics.PresentationTraceSources.SetTraceLevel(myItemsControl.ItemContainerGenerator,System.Diagnostics.PresentationTraceLevel.High) 从立即窗口。这会导致检测逻辑在每个CollectionChanged事件之后运行,因此会降低应用程序的速度。

这是DataGridViewModel类(缩小):

    private const int GRID_HEIGHT_MAX = 390;
    private const int GRID_HEIGHT_MIN = 60;
    private const int ROW_HEIGHT = 22;
    private int prevRowCount;
    private double gridHeight;
    private MainWindowViewModel mainVm;
    private ObservableCollection<MechTestData> gridData;
    public DataGridViewModel(MainWindowViewModel mainVm)
    {
        this.mainVm = mainVm;
        GridHeight = GRID_HEIGHT_MIN;
        gridData = new ObservableCollection<MechTestData>();
        gridData.CollectionChanged += GridDataChanged;
    }
    public double GridHeight
    {
        get
        {
            return gridHeight;
        }
        set
        {
            gridHeight = value;
            OnPropertyChanged("GridHeight");
        }
    }
    public ObservableCollection<MechTestData> GridData
    {
        get
        {
            return gridData;
        }
        set
        {
            gridData = value;
            OnPropertyChanged("GridData");
        }
    }
    private void GridDataChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        // If the grid height is less than or equal to
        // the maximum grid height
        if (gridHeight <= GRID_HEIGHT_MAX + 1)
        {
            // If we added rows, increase the grid height
            if (gridData.Count > prevRowCount)
            {
                GridHeight += ROW_HEIGHT;
                mainVm.WindowHeight += ROW_HEIGHT;
            }
        }

        // if the grid height is less than or equal to
        // the minimum grid height
        if (gridHeight > GRID_HEIGHT_MIN)
        {
            // If we deleted rows, decrease the grid height
            if (gridData.Count < prevRowCount)
            {
                GridHeight -= ROW_HEIGHT;
                mainVm.WindowHeight -= ROW_HEIGHT;
            }
        }

        // Cache the row count
        prevRowCount = gridData.Count;
    }
    public void FillGPLocationAndPrint(Dictionary<string, string> gpLocationToDiePrintMap)
    {
        foreach (KeyValuePair<string, string> map in gpLocationToDiePrintMap)
        {
            GridData.Add(new MechTestData(map.Key, map.Value));
        }
    }

ViewModelBase类:

public abstract class ViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

XAML(减去所有其他组件):

<Window 
x:Class="MechQualTestDataEntry.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:p="clr-namespace:MechQualTestDataEntry.Properties"
xmlns:wpftk="http://schemas.microsoft.com/wpf/2008/toolkit"
xmlns:local="clr-namespace:MechQualTestDataEntry"
Icon="/MechQualTestDataEntry;component/Resources/MechQualIcon.ico"
Title="MainWindow" 
Background="MidnightBlue"
ResizeMode="CanMinimize"
Height="{Binding WindowHeight}"
MinHeight="{Binding WindowHeight}"
MaxHeight="{Binding WindowHeight}"
MinWidth="700"
MaxWidth="1000"
Width="820">
<Window.Resources>
    <local:DateTimeConverter x:Key="DateTimeFormatter"/>
</Window.Resources>

    <!-- Data Grid -->
    <DataGrid
        DockPanel.Dock="Bottom"
        x:Name="grdData"
        CellStyle="{StaticResource cellStyle}"
        FontFamily="Verdana"
        Height="{Binding GridHeight}"
        Foreground="MidnightBlue"
        AutoGenerateColumns="False"
        RowHeight="22"
        CanUserAddRows="True"
        CanUserDeleteRows="True"
        CanUserReorderColumns="False"
        CanUserResizeColumns="False"
        CanUserResizeRows="False"
        CanUserSortColumns="True"
        ItemsSource="{Binding GridData}"
        SelectionUnit="CellOrRowHeader"
        SelectionMode="Extended">
        <DataGrid.Resources>
            <Style TargetType="{x:Type DataGridCell}">
                <EventSetter 
                    Event="PreviewMouseLeftButtonDown" 
                    Handler="DataGridCell_PreviewMouseLeftButtonDown"/>
            </Style>
            <Style TargetType="{x:Type DataGridRowHeader}">
                <Style.Triggers>
                    <Trigger Property="IsMouseOver" Value="False">
                        <Setter Property="Background" Value="DeepSkyBlue" />
                        <Setter Property="BorderBrush" Value="MidnightBlue" />
                        <Setter Property="BorderThickness" Value="1" />
                        <Setter Property="Width" Value="15" />
                        <Setter Property="HorizontalContentAlignment" Value="Right" />
                        <Setter Property="VerticalContentAlignment" Value="Center" />
                    </Trigger>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="MidnightBlue" />
                        <Setter Property="BorderBrush" Value="DeepSkyBlue" />
                        <Setter Property="BorderThickness" Value="1" />
                        <Setter Property="Width" Value="15" />
                        <Setter Property="HorizontalContentAlignment" Value="Right" />
                        <Setter Property="VerticalContentAlignment" Value="Center" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </DataGrid.Resources>
        <DataGrid.Columns>

            <!-- TO Number -->
            <DataGridTextColumn 
                Width="40"
                Binding="{Binding TONumber}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            TextWrapping="Wrap"
                            Text="TO #"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- GelPak Location -->
            <DataGridTextColumn 
                Width="60"
                Binding="{Binding GelPakLocation}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            TextWrapping="Wrap"
                            Text="GelPak Location"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- Die Print -->
            <DataGridTextColumn 
                Width="60"
                Binding="{Binding DiePrint}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            Text="Die Print"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- Wire Pull Test -->
            <DataGridTextColumn 
                Width="70"
                Binding="{Binding WirePullTestValue}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            TextWrapping="Wrap"
                            Text="Wire Pull Test"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- Failure Mode -->
            <DataGridTextColumn 
                Width="84"
                Binding="{Binding FailureMode}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            Text="Failure Mode"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- Ball Shear -->
            <DataGridTextColumn 
                Width="70"
                Binding="{Binding BallShearTestValue}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            TextWrapping="Wrap"
                            Text="Ball Shear Test"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- Die Shear -->
            <DataGridTextColumn 
                Width="70"
                Binding="{Binding DieShearTestValue}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            TextWrapping="Wrap"
                            Text="Die Shear Test"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- InP Remaining -->
            <DataGridTextColumn 
                Width="70"
                Binding="{Binding InPRemaining}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            TextWrapping="Wrap"
                            Text="InP Remaining"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- Test Result -->
            <DataGridTextColumn 
                Width="70"
                Binding="{Binding TestResult}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            TextWrapping="Wrap"
                            Text="Pass/Fail"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>

            <!-- Notes -->
            <DataGridTextColumn
                Width="*"
                Binding="{Binding Notes}">
                <DataGridTextColumn.HeaderTemplate>
                    <DataTemplate>
                        <TextBlock
                            Style="{StaticResource tbkStyleGridHeader}"
                            TextWrapping="Wrap"
                            Text="Notes"/>
                    </DataTemplate>
                </DataGridTextColumn.HeaderTemplate>
            </DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>

任何帮助解决这个问题的人都会非常感激。

此致

凯尔

2 个答案:

答案 0 :(得分:0)

我的问题通过此方法解决了。 去视觉工作室&gt;工具&gt;选项&gt;调试&gt;数据绑定&GT; Vorbose。

答案 1 :(得分:-2)

我想我会回答这个问题,因为我发布这个问题已经有一段时间了。问题是.NET 4.0安装问题。我们在具有此问题的所有计算机上卸载并重新安装了该框架,并修复了该问题。