2016-01-27 177 views
1

我希望只有在修改了某些其他屬性的情況下,才能夠自動將UpdateDate字段的值更新爲當前日期時間。對於這個例子 - 標題。如果一個類包含數十個屬性,其中一半應該觸發UpdateDate值更改,那麼做到這一點的可能方式是什麼?C# - 修改其他屬性時自動更新對象屬性

public class Ticket 
    { 
     public Ticket() { } 

     public int TicketID { get; set; } 
     public string Title { get; set; } 
     public string Description { get; set; } 
     public DateTime UpdateDate { get; set; } 
    } 

回答

2

無需使用INotifyPropertyChanged的。這裏有一個例子,如果「標題」屬性更改,UpdateDate將設置爲「DateTime.Now」

public class Ticket 
{ 
    public int TicketID { get; set; } 
    private string title; 
    public string Title 
    { 
     get { return title; } 
     set 
     {     
      title = value; 
      UpdateDate = DateTime.Now; 
     } 
    } 
    public string Description { get; set; } 
    public DateTime UpdateDate { get; set; } 
} 
+0

您需要確保捕獲每個實例,非常複雜。 – OverMars

0

只需創建一個基類,它從INotifyPropertyChanged接口繼承這樣的:

public abstract class BaseViewModel : INotifyPropertyChanged 
{ 
    #region members 
    protected IUnitOfWork UnitOfWork; 
    #endregion 

    public BaseViewModel() 
    {    
    } 

    //basic ViewModelBase 
    internal void RaisePropertyChanged(string prop) 
    { 
     if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(prop)); } 
    } 
    public event PropertyChangedEventHandler PropertyChanged; 

} 

那麼您可以在您的具體類使用這樣的:

public class TransactionItemViewModel : BaseViewModel 
{ 
    int _Quantity; 
    public int Quantity 
    { 
     get 
     { 
      return _Quantity; 
     } 
     set 
     { 
      if (_Quantity != value) 
      { 
       _Quantity = value; 
       RaisePropertyChanged("Quantity"); 
       RaisePropertyChanged("TotalSalePrice"); 
      } 
     } 
    } 

    public decimal TotalSalePrice 
    { 
     get 
     {         
      return 100 * Quantity; 
     } 
    } 
}