I'm trying to make a sample with eventAggregator and latest Prism v7. The sample is built with the Prism template pack, a page with a button that loads another page, in the button I Publish an event and in the constructor of the second page i Subscribe it, then write on a label if the event has been received.
First Page:
<StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Label Text="Welcome to Xamarin Forms and Prism!" />
<Button Command="{Binding Button1Command}" Text="ContentPage1" />
</StackLayout>
Second page:
<StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Label
HorizontalOptions="CenterAndExpand"
Text="{Binding Message}"
VerticalOptions="CenterAndExpand" />
</StackLayout>
First viewmodel:
public class MainPageViewModel : ViewModelBase
{
IEventAggregator _ea;
public MainPageViewModel(INavigationService navigationService, IEventAggregator eventAggregator)
: base (navigationService)
{
Title = "Main Page";
_ea = eventAggregator;
}
public DelegateCommand<string> Button1Command => new DelegateCommand<string>(Button1Navigate);
private async void Button1Navigate(string par)
{
_ea.GetEvent<BasicEvent>().Publish("basicEvent");
await NavigationService.NavigateAsync("PrismContentPage1");
}
}
Second ViewModel:
public class PrismContentPage1ViewModel : BindableBase
{
IEventAggregator _ea;
private string _message;
public string Message
{
get { return _message; }
set { SetProperty(ref _message, value); }
}
public PrismContentPage1ViewModel(IEventAggregator eventAggregator)
{
_ea = eventAggregator;
_ea.GetEvent<BasicEvent>().Subscribe(OnInitializationEventFired);
}
public void OnInitializationEventFired(string message)
{
Message = "received";
}
}
The label never gets the "received" string. I stripped the code of many other tests: I've added a button in second page to Publish from inside the same ViewModel, and then works. I debugged and inspected the eventAggregator, and if when is initialized in the second page it actually has 1 item, the BasicEvent.
The first time I run it, it doesn't fire the event, then I go back to first page (I know, without unsubscribing), and press the button again, and this second time it gets fired, but yet, Message is not changed in the label.
It seems all very simple, and samples (HamburgerMenu, UsingEventAggregator) work, but not this very basic sample I'm doing, can you help? Thanks