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

时间:2017-08-13 03:45:15

标签: c# xaml uwp background-task

问题:我正在尝试使用其他一些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

我搜索了一下异常,发现为了从非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 个答案:

答案 0 :(得分:4)

我相信您忘了实施XamlRenderingBackgroundTask

  

提供在后台任务中从XAML树创建位图的功能。