C# 如何在UWP后台任务中使用XAML UI元素?
问题:我正在尝试使用一些其他UI元素(主要是文本块)创建网格,然后使用C# 如何在UWP后台任务中使用XAML UI元素?,c#,xaml,uwp,background-task,C#,Xaml,Uwp,Background Task,问题:我正在尝试使用一些其他UI元素(主要是文本块)创建网格,然后使用RenderTargetBitmap渲染网格,最后将其保存到一个图像文件,执行后台任务 以下是该方法的代码: private async Task<bool> RenderGridAsync() { Grid mainGrid = new Grid(); TextBlock tText = new TextBlock() {
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();
}
}
但即使这样,我也有一个例外:
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元素吗?
如果是,我该怎么做?我相信您忘记实施了 提供在后台任务中从XAML树创建位图的功能
这正是我需要的。。!实现XamlRenderingBackgroundTask并重写OnRun(IBackgroundTaskInstance taskInstance)方法解决了我的问题。。!
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