为什么DataGrid空白行会消失?

时间:2016-06-13 13:45:03

标签: c# wpf datagrid observablecollection

我有一个与ObservableCollection绑定的DataGrid。

<DataGrid x:Name="substanceDataGrid" ItemsSource="{Binding StoredSequences}" CanUserResizeColumns="True" CanUserResizeRows="True" CanUserAddRows="True" SelectionMode="Single" >
    <DataGrid.Columns>
        <DataGridTextColumn Header="ID" Binding="{Binding ID}" IsReadOnly="True" >
            <DataGridTextColumn.ElementStyle>
                <Style>
                    <Setter Property="TextBlock.TextWrapping" Value="Wrap" />
                    <Setter Property="TextBlock.TextAlignment" Value="Center"/>
                </Style>
            </DataGridTextColumn.ElementStyle>
        </DataGridTextColumn>
        <DataGridTextColumn Header="Name" Width="120" >
            <DataGridTextColumn.ElementStyle>
                <Style>
                    <Setter Property="TextBlock.TextWrapping" Value="Wrap" />
                </Style>
            </DataGridTextColumn.ElementStyle>
            <DataGridTextColumn.Binding>
                <Binding Path="NameEnglish" UpdateSourceTrigger="LostFocus"/>
            </DataGridTextColumn.Binding>
        </DataGridTextColumn>
    </DataGrid.Columns>
</DataGrid>

在我的ViewModel中,使用OnCollectionChanged添加新行时更新数据库。

private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (e.NewItems != null) // New row added
    {
        BackgroundWorker bw = new BackgroundWorker();
        bw.DoWork += async delegate
        {
            StoredSequences.CollectionChanged -= OnCollectionChanged;
            sequencesDbManager.AddSequence((Sequence)e.NewItems[0]);
            StoredSequences.CollectionChanged += OnCollectionChanged;
        };
        bw.RunWorkerAsync();
    }
}

我提到数据库管理器初始化时引用了ObservableCollection:

sequencesDbManager = new SequencesDatabaseManager(StoredSequences);

并在将新项目添加到数据库后,在SequencesDatabaseManager.AddSequence()内更新集合:

private void UpdateCollection()
{
    System.Windows.Application.Current.Dispatcher.Invoke(delegate
    {
        sequences.Clear();
        foreach (DataRow row in dataTable.Rows)
        {
            sequences.Add(new Sequence
            {
                ID = (int)row["Id"],
                NameEnglish = row["Name (English)"].ToString()
            });
        }
    });
}

问题是添加新项目后,DataGrid末尾的空行消失。我该如何避免这个问题?

0 个答案:

没有答案