[英]How to use MVVM Light Messenger in Windows Phone?
我正在嘗試學習如何在MVVM Light中使用Messenger類別,但是什么也沒發送。
public class MainViewModel : ViewModelBase
{
private readonly INavigationService navigationService = null;
public MainViewModel(INavigationService navigationService)
{
this.navigationService = navigationService;
SecondPgCmd = new RelayCommand(() => SecondPg());
}
private void SecondPg()
{
Messenger.Default.Send<string>("my message");
navigationService.NavigateTo("/Views/SecondPg.xaml");
}
public RelayCommand SecondPgCmd
{
get;
private set;
}
}
public class SecondVm : ViewModelBase
{
/// <summary>
/// Initializes a new instance of the SecondVm class.
/// </summary>
public SecondVm()
{
Messenger.Default.Register<string>(this, x => MyProperty = x);
}
/// <summary>
/// The <see cref="MyProperty" /> property's name.
/// </summary>
public const string MyPropertyPropertyName = "MyProperty";
private string myProperty = "";
/// <summary>
/// Sets and gets the MyProperty property.
/// Changes to that property's value raise the PropertyChanged event.
/// </summary>
public string MyProperty
{
get
{
return myProperty;
}
set
{
if (myProperty == value)
{
return;
}
RaisePropertyChanging(() => MyProperty);
myProperty = value;
RaisePropertyChanged(() => MyProperty);
}
}
}
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
if (ViewModelBase.IsInDesignModeStatic)
{
}
else
{
}
SimpleIoc.Default.Register<INavigationService, NavigationService>();
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<SecondVm>();
}
注冊視圖模型(注冊消息)時,請嘗試將true
作為第一個參數傳遞。 這樣,它們將立即創建並從一開始就注冊消息,而不是在調用視圖時注冊。
SimpleIoc.Default.Register<SecondVm>(true);
請參閱這篇出色的文章,以了解有關消息傳遞的更多信息,其中還將討論此問題。
消息傳遞用於將參數從一項服務傳遞到另一項服務。 在這種情況下,當您想保存數據以備后用時,最好將其保存在某處。 @sibbl提出的解決方案可能會起作用,但是您不必要地創建了一個尚未使用的視圖模型(尚未)並且該解決方案無法擴展。
由於您已經有了SimpleIoc
,因此只需創建一個新對象並將其放入其中。 像這樣:
class ImportantMessageService
{
public string Message { get; set; }
}
// in locator
SimpleIoc.Default.Register<ImportantMessageService>();
// in page 1
var service = SimpleIoc.Default.GetInstance<ImportantMessageService>();
service.Message = "Hello world";
// in page 2
var service = SimpleIoc.Default.GetInstance<ImportantMessageService>();
MessageBox.Show(service.Message);
這樣,通信中的所有參與者都使用中央服務來保存數據。 這樣可以很好地進行擴展,因為萬一您從不進入第二頁,數據就不會被使用。 您唯一需要擔心的是墓碑。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.