2015-09-07 41 views
0

我有一個DataGrid,其ItemsSource設置爲自定義對象的ObservableCollection,該對象從窗口傳遞到包含DataGrid的usercontrol,並且此工作非常順利以及更改註冊在兩個方向我想有能力取消任何更改在我的用戶控制,如果我點擊取消按鈕。取消或保存對DataGrid中的自定義對象所做的更改

有沒有辦法推遲我在我的DataGrid中對我的父窗口中的ItemSource所做的任何更改?或者相反,如果我願意,可以通過某種方式取消更改。任何幫助將不勝感激,這是我目前的代碼;

public UserControl1(ObservableCollection<ContourControl.RectangleContour> list1) 
    { 
     InitializeComponent(); 
     itemCollectionViewSource = (CollectionViewSource)(FindResource("ItemCollectionViewSource")); 

     itemCollectionViewSource.Source = list1; 

     //here i create some columns and bind the data 

     DataGridViewer.ItemsSource = list1; 
     DataGridViewer.AutoGenerateColumns = false; 

    } 

    private void Cancel(object sender, RoutedEventArgs e) 
    { 
     //if i click this i would like any changes to list1 to be reverted or ignored 

     Window parentWindow = Window.GetWindow((DependencyObject)sender); 
     if (parentWindow != null) 
     { 
      parentWindow.Close(); 
     } 
    } 

    private void OK(object sender, RoutedEventArgs e) 
    { 
     //if i click this i would like the changes to carry on to my list, as it currently does instantly 

     Window parentWindow = Window.GetWindow((DependencyObject)sender); 
     if (parentWindow != null) 
     { 
      parentWindow.Close(); 
     } 
    } 

這裏是啓動我的用戶,並通過原始列表我已經存儲在數據中的代碼。

   Window window = new Window 
      { 
       Height = 200, 
       Width = 765, 
       Content = new UserControl1(list1: rectContourList), 
      }; 
      window.ShowDialog(); 
+0

你基本上詢問如何實現撤消功能。這個問題已經處理:http://stackoverflow.com/questions/7984674/datagrid-and-mvvm-with-undo-redo –

回答

0

您可以設置UpdateSourceTrigger=Explicit你的文本。

<TextBox Name="tb1" Text="{Binding tbval, UpdateSourceTrigger=Explicit}"/> 

然後點擊「確定」按鈕,點擊更新源,如果你想顯示在文本框中的前值

private void OK_Button_Click(object sender, RoutedEventArgs e) 
     { 
      BindingExpression binding = tb1.GetBindingExpression(TextBox.TextProperty); 
      binding.UpdateSource(); 
     } 

而「取消」剛剛創下的屬性後面,你還能只是把它留空。

private void Cancel_Button_Click_1(object sender, RoutedEventArgs e) 
     { 
      //tbval is the property binded to Textbox 
      tbval = tbval; 
     } 

https://msdn.microsoft.com/en-us/library/system.windows.data.binding.updatesourcetrigger.aspx

相關問題