2017-01-08 36 views
0

我工作的窗口有一個DataGrid綁定到一個可觀察集合,該集合包含源自數據庫表的項目。我想在輸入網格中的一行時記住原始項目,並且當網格中的行保留時,我想將添加或更新的項目提交到數據庫。我需要原始和修改的值來找出發生了什麼變化。WPF DataGrid行輸入和行離開事件

基本上,我想要在數據表中輸入數據時,實現與Visual Studio或SQL Developer Studio中相同的行爲。

有誰知道該怎麼做?謝謝。

在我當前的實現中,當字段發生更改時,我無法獲得項目的原始值,並且每個更改的字段都會調用OnItemChanged,我寧願一次提交整行。

這是我的觀點:

<Window x:Class="TourMan.Views.EditPersonsView" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" 
    Title="Persons"> 
    <Grid> 
     <DataGrid AutoGenerateColumns="False" HorizontalContentAlignment="Center" ItemsSource="{Binding Persons}" 
     RowBackground="LightGoldenrodYellow" AlternatingRowBackground="PaleGoldenrod" AlternationCount="2" 
      CanUserAddRows="True" CanUserDeleteRows="True" > 
      <DataGrid.Columns> 
       <DataGridTextColumn Header="Name" Width ="100" Binding="{Binding Name}"/> 
       <DataGridTextColumn Header="Address" Width ="250" Binding="{Binding Addresses}"/> 
      </DataGrid.Columns> 
     </DataGrid> 
    </Grid> 
</Window> 

和視圖模型:

class EditPersonsViewModel 
{ 
    public ObservableCollection<Person> Persons { get; } 

    public EditPersonsViewModel() 
    { 
     Persons = Engine.Instance().GetPersons(); 
     foreach (var person in Persons) 
     { 
      person.PropertyChanged += OnItemChanged; 
     } 
     Persons.CollectionChanged += OnCollectionChanged; 
    } 

    private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
    { 
     if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems != null) 
     { 
      foreach (var item in e.NewItems) 
      { 
       Engine.Instance().AddPerson((Person)item); 
       ((Person)item).PropertyChanged += OnItemChanged; 
      } 
     } 
     else if (e.Action == NotifyCollectionChangedAction.Remove && e.OldItems != null) 
     { 
      foreach (var item in e.OldItems) 
      { 
       Engine.Instance().DeletePerson(((Field)item)); 
      } 
     } 
    } 

    private void OnItemChanged(object sender, PropertyChangedEventArgs e) 
    { 
     Engine.Instance().UpdatePerson((Person)sender, null); 
    } 
} 

回答

0

一個漫長而痛苦的搜索,我發現這裏的解決方案https://www.codeproject.com/kb/wpf/wpfdatagridexamples.aspx後,這是真的很酷,所以我想分享它。

集合中的項需要實現IEditableObject。然後datagrid將在行編輯開始時調用BeginEdit(),並在編輯結束時調用EndEdit()。查看這篇偉大文章中的所有詳細信息。