【发布时间】:2018-01-23 09:45:56
【问题描述】:
我正在尝试使用 eventAggregator 和最新的 Prism v7 制作示例。 该示例是使用 Prism 模板包构建的,一个带有加载另一个页面的按钮的页面,在按钮中我发布一个事件,在第二个页面的构造函数中订阅它,然后在收到事件时写在标签上.
首页:
<StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Label Text="Welcome to Xamarin Forms and Prism!" />
<Button Command="{Binding Button1Command}" Text="ContentPage1" />
</StackLayout>
第二页:
<StackLayout HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand">
<Label
HorizontalOptions="CenterAndExpand"
Text="{Binding Message}"
VerticalOptions="CenterAndExpand" />
</StackLayout>
第一个视图模型:
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");
}
}
第二个视图模型:
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";
}
}
标签永远不会得到“received”字符串。 我剥离了许多其他测试的代码:我在第二页中添加了一个按钮以从同一个 ViewModel 中发布,然后就可以工作了。 我调试并检查了 eventAggregator,如果在第二页初始化时它实际上有 1 个项目,即 BasicEvent。
我第一次运行它时,它没有触发事件,然后我回到第一页(我知道,没有取消订阅),再次按下按钮,第二次它被触发,但是,标签中的消息未更改。
看起来一切都很简单,示例(HamburgerMenu,UsingEventAggregator)可以工作,但不是我正在做的这个非常基本的示例,你能帮忙吗? 谢谢
【问题讨论】:
标签: mvvm xamarin.forms prism