我正在尝试使用消息中心通过消息中心发送一个简单的字符串。它有效。但是由于某种原因,尽管只发送了一条消息,但它被捕获了两次。
这是发送页面:
protected override void OnAppearing()
{
base.OnAppearing();
MessagingCenter.Subscribe<App, string>(this, "Barcode", (sender, arg) => {
Device.BeginInvokeOnMainThread(() =>
{
HandleReadLabel(arg);
});
});
viewModel.LoadItemsCommand.Execute(null);
}
protected override void OnDisappearing()
{
base.OnDisappearing();
MessagingCenter.Unsubscribe<App, string>(this, "Barcode");
}
public async Task<bool> HandleReadLabel(string labelText)
{
await Navigation.PopAsync();
MessagingCenter.Send<App, string>((App)Application.Current, "Trolley", labelText);
return true;
}
private async void btnTest_Clicked(object sender, EventArgs e)
{
string LabelTrolley = (sender as Button).Text;
await Navigation.PopAsync();
MessagingCenter.Send<App, string>((App)Application.Current, "Trolley", LabelTrolley);
}
发送该消息的两种方式:单击按钮,或使用链接到设备的条形码扫描仪(我对该订阅没有问题,但我比较了两者并找不到问题)
然后是接收页面:
public Inv2Page(bool isMoveGoods)
{
InitializeComponent();
if (isMoveGoods)
viewModel = new Inv2ViewModel(ItemsListView, ItemsListViewTransfer, SelectionBinBoxView, "Move Goods");
else
viewModel = new Inv2ViewModel();
viewModel.LabelBin = "SCAN";
viewModel.IsMoveGoods = isMoveGoods;
BindingContext = viewModel;
MessagingCenter.Unsubscribe<App, string>(this, "Trolley");
MessagingCenter.Subscribe<App, string>(this, "Trolley", (sender, arg) => {
Device.BeginInvokeOnMainThread(() =>
{
HandleReadLabel(arg);
viewModel.LoadItemsCommand.Execute(null);
});
});
}
没有退订就消失了。
订阅的页面总是在订阅的后面,当我从订阅中得到我想要的答案时,它会将消息发回并消失。然后它会触发两次结果。