【问题标题】:Can't Insert or Delete from my WPF DataGrid无法从我的 WPF DataGrid 中插入或删除
【发布时间】:2011-12-25 20:04:05
【问题描述】:

我有一个 WPF DataGrid,我希望能够对其进行更新、插入和删除。我使用 ObservableCollection 绑定到 DataGrid.DataContext。

当 DataGrid 的 SelectionChanged() 事件触发时,我执行 Context.SaveChanges() 以写回数据库。

但是,上述方法仅在我更新现有记录时有效。当我尝试通过单击 DG 中的最后一行或按删除来添加新记录时,SaveChanges() 不执行任何操作。数据未添加或删除。

如何在 DataGrid 中添加或删除记录?这是我的 DG xaml:

        <DataGrid AutoGenerateColumns="False" Margin="0,12,0,89" Name="grdContact" 
                          CanUserAddRows="True" SelectionMode="Single" IsReadOnly="False"     CanUserDeleteRows="True"
                          ItemsSource="{Binding}"
                          IsSynchronizedWithCurrentItem="True"
                          Focusable="True"
                          SelectionChanged="grdContact_SelectionChanged"

            <DataGrid.Columns>

            <DataGridTextColumn Header="Last Name" Width="150" Binding="{Binding LastName}"/>
            <DataGridTextColumn Header="First Name" Width="150" Binding="{Binding FirstName}"/>
        </DataGrid.Columns>
    </DataGrid>

我的代码背后 - 伪代码:

private void Window_Loaded(object sender, RoutedEventArgs e)
{
            var CustomerObj = new ObservableCollection<Contact>(GetContacts());
            grdContact.DataContext = CustomerObj;
}

    private void grdContact_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        Context.SaveChanges();
    }

【问题讨论】:

标签: wpf


【解决方案1】:

这是因为ObservableCollection&lt;T&gt; 不会通知添加或删除项目的上下文。事实上,它对您的数据库上下文一无所知!

您必须连接 CustomerObj 集合才能在上下文中添加或删除对象:

CustomerObj.CollectionChanged += CustomerObj_CollectionChanged;
...

private void CustomerObj_CollectionChanged(object sender,
    NotifyCollectionChangedEventArgs e)
{
    switch (e.Action)
    {
        case NotifyCollectionChangedAction.Add:
            foreach (var item in e.NewItems.Cast<Contact>())
                Context.AddObject(item);
            break;
        case NotifyCollectionChangedAction.Remove:
            foreach (var item in e.OldItems.Cast<Contact>())
                Context.DeleteObject(item);
            break;
        // handle Replace, Move, Reset
    }

    Context.SaveChanges();
}

【讨论】:

    【解决方案2】:

    我遇到了非常相似的问题。 当 getContacts() 返回 List 我只能更新(不能插入或删除)。 但是当 getContects 返回 IQueryable 时,一切都很完美(但我无法排序:()

    【讨论】:

      猜你喜欢
      • 2015-01-21
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 2015-03-26
      • 2010-11-13
      • 1970-01-01
      • 2019-02-01
      相关资源
      最近更新 更多