2013-04-06 134 views
0

我目前正在使用MVVM模式進行編程。動態視圖?在哪裏放邏輯?

我的觀點模型看起來像這樣

class DoorsViewModel 
{ 
ObservableCollection<Door> doorCollection; 
}; 

大門類看起來像下面

class Door 
{ 
string name; 
bool isOpen; 
}; 

我的看法是鏈接到視圖模型,並簡單地包含圖片和名稱的longlistselector的門。我希望圖片是動態的,並根據門的狀態(無論是打開還是關閉)進行更改。我將如何實現它,以便根據門的狀態動態更新圖片?這應該在視圖模型中完成嗎?還是應該在視圖內完成?

回答

2

這個邏輯應該在ViewModel中。與視圖相關的所有邏輯或者顯示方式應該在ViewModel中。視圖中沒有邏輯(.xaml.cs)。

您通常使用INotifyPropertyChanged接口來通知視圖有變化。在這種情況下,您想要在門的狀態改變時更改門圖像。在這種情況下,我會嘗試這樣的事情。

class Door: INotifyPropertyChanged 
{ 
    private string _name; 
    private bool _isOpen; 

    public Uri DoorImage 
    { 
     get 
     { 
      if (_isOpen) return new Uri("uri_to_open.png"); 
      return new Uri("uri_to_closed.png"); 
     } 
    } 

    public bool IsOpen 
    { 
     get { return _isOpen; } 
     set 
     { 
      _isOpen = value; 
      RaisePropertyChanged("IsOpen"); 
      // important, notifies the UI to update the door image 
      RaisePropertyChanged("DoorImage"); 
     } 
    } 

    private void RaisePropertyChanged(string propertyName) 
    { 
     var tmp = PropertyChanged; 
     if (tmp != null) tmp(this, new PropertyChangedEventArgs(propertyName)); 
    } 

    public event PropertyChangedEventHandler PropertyChanged; 
}; 

注:我已經將字段封裝到屬性中。

如果您的圖片嵌入到您的圖片中,請查看link以瞭解如何爲圖片編寫圖片。