[英]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.