【问题标题】:Xamarin - Function inside Device.BeginInvokeOnMainThread not calling correctlyXamarin - Device.BeginInvokeOnMainThread 中的函数未正确调用
【发布时间】:2018-12-08 13:45:54
【问题描述】:

我正在 Xamarin 中创建 QR 码,并在 Device.BeginInvokeOnMainThread 中调用 QR 码的生成,以便在每次添加新输入时动态更新 QR 码。

Device.BeginInvokeOnMainThread(async () =>
            {
                QRCodeView.IsVisible = true;
                QRCodeView = null;
                QRCodeView = new ZXingBarcodeImageView
                {
                    BarcodeFormat = BarcodeFormat.QR_CODE,
                    BarcodeOptions = new QrCodeEncodingOptions
                    {
                        Height = 150,
                        Width = 150,
                        PureBarcode = true
                    },
                    BarcodeValue = await SetQrContent(),

                    VerticalOptions = LayoutOptions.CenterAndExpand,
                    HorizontalOptions = LayoutOptions.CenterAndExpand
                };
            });

在我的函数SetQrContent() 中,二维码被传递了新值。 但是我认为这个函数调用得太晚了,因为新二维码的值没有正确设置,导致我的二维码在输入改变时没有改变。

我使用BeginInvokeOnMainThread 错了吗?

【问题讨论】:

  • 在开始调用 MainThred 之前,您是否尝试过运行 SetQrContent?
  • 感谢评论,问题依旧
  • IsVisible 属性赋值不合理,它属于 新语句之后。也是放置断点以确保代码实际执行的好地方。异步代码有隐藏异常的诀窍,如果你不检查它们,它们就会落入比特桶中。

标签: c# multithreading xamarin xamarin.forms invoke


【解决方案1】:

在更改 QrContent 时尝试仅设置 BarcodeValue

Device.BeginInvokeOnMainThread(async () =>
{
    // Don't reset the view, only reset the value on the barcode
    QRCodeView.BarcodeValue = await SetQrContent();
});

当控件已经添加到页面时,只更改视图的属性而不是创建新视图。当您创建新的ZXingBarcodeImageView 时,新视图并未添加到页面中,导致仍然看到旧数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-25
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    • 1970-01-01
    • 2017-07-27
    相关资源
    最近更新 更多