簡體   English   中英

根據按鈕的存在,持久對象從子窗體更改為父窗體

[英]Persisting object changes from child form to parent form based on button press

我創建了一個用於添加和編輯自定義對象的表單。 表單采用哪種模式由調用代碼傳遞的枚舉值提供。 我還傳入了自定義類型的對象。 我所有的數據控件都綁定到自定義對象的特定屬性。 當表單處於“添加”模式時,這非常有用,就像用數據更新控件時一樣,基礎對象也是如此。 但是,在“編輯”模式下,我保留調用代碼提供的自定義對象的兩個變量,即原始變量和通過深度復制生成的臨時變量。 然后將控件綁定到臨時副本,如果用戶單擊“取消”按鈕,則可以輕松放棄更改。 我想知道的是,如果用戶單擊“確定”按鈕,如何將這些更改保存回原始對象,因為由於深度復制,現在斷開了連接。 如果可以的話,我試圖避免在“添加/編輯”表單上實現內部屬性。 以下是我的代碼示例:


public AddEditCustomerDialog(Customer customer, DialogMode mode)
{
   InitializeComponent();
   InitializeCustomer(customer, mode);
}
private void InitializeCustomer(Customer customer, DialogMode mode)
{
   this.customer = customer;
   if (mode == DialogMode.Edit)
   {
      this.Text = "Edit Customer";
      this.tempCustomer = ObjectCopyHelper.DeepCopy(this.customer);
      this.customerListBindingSource.DataSource = this.tempCustomer;
      this.phoneListBindingSource.DataSource = this.tempCustomer.PhoneList;
   }
   else
   {
      this.customerListBindingSource.DataSource = this.customer;
      this.phoneListBindingSource.DataSource = this.customer.PhoneList;
   }
}

您始終可以將函數添加為對象(“客戶”),例如“復制(客戶cust)”或“更新(客戶cust)”,然后以這種方式使用更改。

另一種方法是在Customer EditableCustomer周圍有一個包裝器類,該包裝器類在其構造函數EditableCustomer(Customer root)中使用一個客戶對象,並使用該對象保存更改。 在最后一個事件中,只需調用“ UpdateRoot()”之類的函數,然后將更改填充回原始客戶,否則,將其與丟棄相同。

您將無法直接使用深層副本,但這將允許您控制這種情況,並且實際上允許您動態地控制編輯和撤消操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM