我有一个ZXing扫描仪页面,我想将扫描数据从ScanPageModel获取到MyPageModel
我正在从MyPageModel打开扫描页面
public Command ScanCode
{
get
{
return new Command(async () =>
{
MessagingCenter.Subscribe<MyPageModel>(this, "ScanText", (value) =>
{
});
await CoreMethods.PushPageModel<ScanPageModel>();
});
}
}
从ScanPageModel获得扫描结果后,发送消息传递中心数据
private void ScanResultAction(object obj)
{
// Prevent multiple event triggers from triggering the navigation multiple times
if (NavigatingAway)
return;
NavigatingAway = true;
var result = obj as ZXing.Result;
var format = result?.BarcodeFormat.ToString() ?? string.Empty;
var value = result?.Text ?? string.Empty;
// Navigate to a page based on value
SampleListData sa = new SampleListData();
sa.Name = value;
Device.BeginInvokeOnMainThread(async () =>
{
MessagingCenter.Send<ScanPageModel, string>(this, "ScanText", result.Text);
await CoreMethods.PopPageModel();
});
}
但是从ScanPageModel发送数据后没有调用我的消息传递中心 这是用于接收扫描代码的订阅方法
public MyPageModel()
{
MessagingCenter.Subscribe<SampleListData>(this, "ScanText", (value) =>
{
});
}
我还尝试将此订阅放置在
public override void Init(object initData)
{
MessagingCenter.Subscribe<SampleListData>(this, "ScanText", (value) =>
{
});
}
但是它也不起作用 那么如何解决呢?
答案 0 :(得分:0)
您的订阅和发送方法不同。您发送一条消息,但从不听。另一方面,您正在订阅一条从未发送过的消息。让我解释一下。
1。简单字符串消息(不带参数):
订阅:
MessagingCenter.Subscribe<MainPage> (this, "MyMessage", (sender) => {
// do something whenever the "MyMessage" message is sent
});
发送:
MessagingCenter.Send<MainPage> (this, "MyMessage");
2。带有参数的消息:
订阅:
MessagingCenter.Subscribe<MainPage, string> (this, "MyMessageArg", (sender, arg) => {
// do something whenever the "MyMessageArg" message is sent
// using the 'arg' parameter which is a string
string s = arg as string; // s = "John"
});
发送:
MessagingCenter.Send<MainPage, string> (this, "MyMessageArg", "John");
查看这两种类型的<..>内部内容。在第二种类型中,还有您要发送的参数的数据类型。在您的示例中,您将这两种类型混合使用。因此将您的订阅方法更改为:
MessagingCenter.Subscribe<SampleListData, string>(this, "ScanText", (sender, arg) =>{
string data = arg as string;
// do work
});
提示:
退订
MessagingCenter.Unsubscribe<MainPage> (this, "MyMessage");
MessagingCenter.Unsubscribe<MainPage, string> (this, "MyMessageArg");