如何在UWP后台任务中使用XAML UI元素?
问题描述:
问题:我试图创建一些其他的UI元素的网格(的TextBlocks大部分),然后使用RenderTargetBitmap
呈现电网和最后将它保存为图像文件,在后台任务如何在UWP后台任务中使用XAML UI元素?
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()方法调用此方法
我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元素? 如果是,我该怎么做?
这正是我需要的..!实现XamlRenderingBackgroundTask并重写OnRun(IBackgroundTaskInstance taskInstance)方法解决了我的问题。 – Pratyay