我正在尝试学习如何在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>();
}
答案 0 :(得分:0)
在注册视图模型时尝试传递true
作为第一个参数,注册消息。这样,它们将立即创建并从头开始注册消息,而不是在调用视图时注册。
SimpleIoc.Default.Register<SecondVm>(true);
请参阅this great article以了解有关消息传递的更多信息,此问题也在讨论中。
答案 1 :(得分:0)
消息传递用于将参数从一个服务传递到另一个服务。在这种情况下,当您想要保存数据供以后使用时,最好将其保存在某处。 @sibbl提出的解决方案可能有效,但您不必要地创建一个尚未使用的视图模型,并且解决方案无法扩展。
由于您已经拥有SimpleIoc
,只需创建一个新对象并将其放入其中即可。 Lke this:
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);
通过这种方式,通信中的所有参与者都使用中央服务来保存数据。这很好地扩展,因为如果你从未进入第二页,数据就不会被使用了。你唯一需要担心的是墓碑。