前一篇文章提到了如何利用 Caliburn.Micro 做 View 與 View Model 的 binding,但 App 通常不會只有一個頁面,而 Caliburn.Micro 簡化了 Navigation,可以讓程式設計師輕易的做換頁。
在開始介紹之前,先修改 App.xaml.cs 底下 OnLaunched 的程式碼:
if (e.PreviousExecutionState != ApplicationExecutionState.Running)
{
//DisplayRootViewFor<MainPageViewModel>();
DisplayRootView<MainPage>();
}修改後,換頁的效果才會出來。之後在主頁面的 MainPageViewModel 中加上 MyButton 這個 method,這是要給按鈕使用的,程式碼如下:
public void MyButton()
{
this.navigationService.NavigateToViewModel(typeof(SecondPageViewModel), "aaa3");
}第一個參數為 View Model 的型別,第二個則是要傳給下一個 View Model 的參數,這邊是單純丟一個字串。接下來宣告SecondPageViewModel ,並且宣告一個名稱為 Parameter 的屬性。
public class SecondPageViewModel : Screen
{
private INavigationService navigationService;
public SecondPageViewModel(INavigationService navigationService)
{
this.navigationService = navigationService;
}
protected override void OnViewLoaded(object view)
{
this.DisplayTextBlock = this.Parameter;
}
public string Parameter { get; set; }
private string _displayTextBlock;
public string DisplayTextBlock
{
get { return this._displayTextBlock; }
set
{
this._displayTextBlock = value;
NotifyOfPropertyChange("DisplayTextBlock");
}
}
public void GoToThirdPageButton()
{
this.navigationService.NavigateToViewModel<ThirdPageViewModel>();
}
}特別要注意的是,Parameter 要在 OnViewLoaded 這個 Event 之後才會有值,在建構子中它會是 null。
在下一篇文章,將會介紹 Event 的設定。
文章標籤
全站熱搜
