Xamarin开发,使用MessageCenter在ViewModel和View之间传递值

最近在学习Xamarin.Forms的开发,并且使用MVVM的结构。在学习的过程中发现页面的点击命令都在ViewModel中的Command实现,如果想要点击按键之后实现页面的跳转,必须在UI层调用 Navigation.Push方法才能实现。后来想想可以用MessageCenter实现。下面是实现方法:

首先定义一个传递的数据类,

public class NavigationMessage  
{  
    public object Paremeter { get; set; }  
}  

在ViewModel中输入发现送消息代码,可放在某个点击命令中,

MessagingCenter.Send<NavigationMessage>(new NavigationMessage() { Paremeter = "hello" },  "Test");  

在View中订阅该消息通知,

protected override void OnAppearing()  
{  
    SubscribeToMessages();  
    base.OnAppearing();  
}  
  
protected override void OnDisappearing()  
{  
    UnsubscribeToMessages();  
    base.OnDisappearing();  
}  
  
private void SubscribeToMessages()  
{  
    MessagingCenter.Subscribe<NavigationMessage>(this, "Test", (args) => {  
        Navigation.PushAsync(new TestPage());//跳转到新的页面  
    });  
}  
  
private void UnsubscribeToMessages()  
{  
    MessagingCenter.Unsubscribe<NavigationMessage>(this, "Test");  
}  
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s