2013-12-12 54 views
0

我想在我正在使用Caliburn Micro的Windows應用商店應用程序中實現註銷功能。重置由Caliburn Micro創建的ViewModels

我遇到的挑戰是,如果用戶註銷,然後以另一個用戶身份再次登錄,則應用程序啓動時實例化的ViewModels仍然存在於內存中,並且對舊模型有引用。因此,視圖正在顯示第一個用戶的陳舊數據。

爲了更好地解釋自己:

public class LoginViewModel : Screen 
{   
    private User _model; 

    // Property gets initialised only on instantiation of ViewModel class 
    public User Model 
    { 
     get { return _model; } 
     set 
     { 
      if (Equals(value, _model)) return; 
      _model = value; 
      NotifyOfPropertyChange(() => Model); 
     } 
    } 

    // ViewModel constructor - instantiated once only by Caliburn on startup 
    public LoginHeaderViewModel(IAuthService authService) 
    { 
     Model = _authService.User; 
    } 
} 

當我的應用程序首次發佈,卡利會自動實例LoginViewModel並運行它的構造,進而獲取登錄的用戶的電流。在用戶註銷並且另一個用戶登錄後,LoginViewModel在運行時不會再次實例化,因爲它已經存在。 Model屬性不被重新評估,因此關聯的視圖不會被告知自行刷新。

我嘗試在註銷時重新創建Caliburn的WinRTContainer,但應用程序開始表現得很有趣。我懷疑無論如何都要採取這種方法,所以並沒有太多注意。

回答

1

我解決我最初的問題(有很多方法可以這樣做)的方式是使用Caliburn事件聚合。

我第一次開始通過創建一個事件:

public class LoginEvent 
{ 
    public bool IsloggedIn { get; set; } 

    public LoginEvent(bool isloggedIn) 
    { 
     IsloggedIn = isloggedIn; 
    } 
} 

當用戶登錄時,我要確保我發佈的登錄事件的實例:

public LoginViewModel(IEventAggregator events) 
{ 
    _events = events; 
} 

public async void SignIn() 
{ 
    // Do login logic ... 
    _events.Publish(new LoginEvent(true)); 
} 

在視圖模型是每當新用戶登錄時都需要休息,確保我訂閱LoginEvent以在模型被觸發時重新初始化我的模型。 ViewModel收聽事件必須實現IHandle<T>接口。

public class DependentViewModel : IHandle<LoginEvent> 
{ 
    public DependentViewModel(IEventAggregator eventAggregator) 
    { 
     eventAggregator.Subscribe(this); 
     InitialiseViewModel(); 
    } 

    public async void InitialiseViewModel() 
    { 
     // Initialise all your model objects here... 
    } 

    public async void Handle(LoginEvent ev) 
    { 
     if (ev.IsloggedIn) 
     { 
      InitialiseViewModel(); 
     } 
    } 
} 
0

什麼Lifestyle做你的ViewModel對象有?

也有override方法,如OnDeactivate,你可以用它來清理用戶特定的設置,take a look here特別是在屏幕節方法,您可以override

+0

'OnDeactivate'將允許我清除我擁有的任何模型。但是,我需要重置或重新初始化我的模型。我想這可以在'OnActivate'中完成 – Hady