如何在UWP后台任务中使用XAML UI元素?

3

问题: 我正在尝试创建一个带有其他UI元素(大多数是TextBlocks)的网格,然后使用RenderTargetBitmap来渲染网格,并最终将其保存为图像文件,在后台任务上。

这是该方法的代码:

  private async Task<bool> RenderGridAsync()
  {
            Grid mainGrid = new Grid();
            TextBlock tText = new TextBlock()
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                TextWrapping = TextWrapping.Wrap,
                Text = "Some Example Text",
                VerticalAlignment = VerticalAlignment.Top,
                FontSize = 72,
                FontWeight = FontWeights.SemiLight
            };
            mainGrid.Children.add(tText);
            RenderTargetBitmap rtb = new RenderTargetBitmap();
                await rtb.RenderAsync(mainGrid);

                var pixelBuffer = await rtb.GetPixelsAsync();
                var pixels = pixelBuffer.ToArray();
                var displayInformation = DisplayInformation.GetForCurrentView();
                var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("CurrentImage" + ".png", CreationCollisionOption.ReplaceExisting);
                using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
                {
                    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
                    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                         BitmapAlphaMode.Premultiplied,
                                         (uint)rtb.PixelWidth,
                                         (uint)rtb.PixelHeight,
                                         displayInformation.RawDpiX,
                                         displayInformation.RawDpiY,
                                         pixels);
                    await encoder.FlushAsync();
                }
}

但是,当我从后台任务的Run()方法中调用此方法时,我会收到以下错误: enter image description here 我在Google上搜索了一下这个异常,发现为了从非UI线程更新UI元素,我需要使用以下内容:
 await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher
                .RunAsync(CoreDispatcherPriority.Normal, async () => {
                await RenderGridAsync();
            });

但是即使这样,仍然会出现异常:

Exception thrown: 'System.Runtime.InteropServices.COMException' in BackgroundTask.winmd
WinRT information: Could not create a new view because the main window has not yet been created

我理解的是,必须先创建视图才能将UI元素添加到其中,但我需要在后台任务中渲染网格并将其保存为图像。之前,在Windows Phone 8.1中,我没有遇到任何问题。

是否不可能在后台任务或非UI任务中使用UI元素? 如果可以,我该如何做?

1个回答

4

2
这正是我所需要的!实现XamlRenderingBackgroundTask并重写OnRun(IBackgroundTaskInstance taskInstance)方法解决了我的问题! - Pratyay

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接