2016-08-01 73 views
0

我的VS2015解決方案由兩個項目組成:DataModel和DesktopClient。 DataModel有一個Customer類 - 這是一個EntityFramework 6 DB實體。客戶擁有FirstName屬性。 在DesktopClient中有一個擴展類CustomerExt。 在DesktopClient中,是否可以通知CustomerExt.FirstName更改?跨兩個項目定義部分客戶將不起作用 - 首先編譯DataModel,並且不會在DesktopClient中定義部分屬性。PropertyChanged擴展類

public class CustomerExt : Customer, INotifyPropertyChanged 
{ 

    public object Clone() 
    { 
     return this.MemberwiseClone(); 
    } 

    private bool _isChecked; 
    public bool IsChecked 
    { 
     get { return _isChecked; } 
     set 
     { 
      this._isChecked = value; 
      NotifyPropertyChanged("IsChecked"); 
     } 
    } 

    #region INotifyPropertyChanged 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged(String info) 
    { 
     this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(info)); 
    } 
} 
+0

不是EntityFramework生成實現'INotifyPropertyChanged'的類嗎? –

+0

不,由於某種原因,我沒有它(DataModel不是我的構建),並且無法覆蓋...也許這就是我應該檢查的 –

回答

0

讓我看看我是否理解,當數據庫上的日期更新時,你想更新視圖?

你必須找到一種方法從你的ViewModel請求這些信息。

某種RefreshFirstNameAsync

private string _firstName; 
public string FirstName 
{ 
    get { return _firstName; } 
    set 
    { 
     this._firstName= value; 
     NotifyPropertyChanged("FirstName"); // There is better ways to implement that line 
    } 
} 

private void RefreshFirstName(){ 
FirstName = _userRepo.GetFirstNameAsync(); 
} 
0

不幸的是,如果你的基類不執行INotifyPropertyChanged最安全的辦法是隻寫一個包裝類,只用在您的軟件。您可以將它與您的CustExt匹配,或者如果您覺得您需要額外的圖層,可以將它分開。

這還假定,而你可能無法控制客戶類,可以控制所有的代碼創建/編輯客戶實例,這樣就可以使用這個新類代替,然後將其轉換爲原始Customer類僅在需要時(如數據庫事務)。

public class CustomerExt: INotifyPropertyChanged 
{ 
    Customer _customer = new Customer(); 

    public object Clone() 
    { 
     return this.MemberwiseClone(); 
    } 

    private bool _isChecked; 
    public bool IsChecked 
    { 
     get { return _isChecked; } 
     set 
     { 
      this._isChecked = value; 
      NotifyPropertyChanged("IsChecked"); 
     } 
    } 

    #region WrapperProperties 

    public bool FirstName 
    { 
     get { return _customer.FirstName; } 
     set 
     { 
      _customer.FirstName= value; 
      NotifyPropertyChanged("FirstName"); 
     } 
    } 

    #endregion 

    public Customer ToCustomer() 
    { 
     // returning a copy of the _customer instance here is safer than returning 
     // the reference, otherwise the properties could be altered directly 
    } 


    #region INotifyPropertyChanged 

    ... 
} 

一些這樣會稍微更容易,如果你有一個ICustomer接口,並在調用數據庫所使用,那麼你可以跳過保留了客戶實例的手續。

我記得有一些第三方庫試圖使這個過程自動化 - 但我從來沒有試過它們和/或不相信它們正常工作。