可以以编程方式创建和呈现Xaml控件吗?

时间:2018-01-03 14:04:36

标签: c# xaml uwp uwp-xaml

是否可以独立于页面创建和呈现UI Xaml控件?

以UWP单元测试为例......

    [TestMethod]
    public async Task TestWebView()
    {
        var taskSource = new TaskCompletionSource<object>();
        await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
            CoreDispatcherPriority.Normal, async () =>
            {
                try
                {
                    var text = new TextBox();
                    text.Text = "hello";

                    var renderer = new RenderTargetBitmap();
                    await renderer.RenderAsync(text);
                }
                catch (Exception e)
                {
                    taskSource.SetException(e);
                }
            });
        await taskSource.Task;
    }

此示例在调用RenderAsync时抛出以下异常:

  

System.ArgumentException:值不在预期范围内。

1 个答案:

答案 0 :(得分:1)

如果要使用RenderAsync方法渲染UIElement的快照,则此UIElement应位于可视树中。这意味着您需要在创建后将其添加到可视树中。请参阅以下代码示例:

<Grid x:Name="root" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Image x:Name="img"></Image>
</Grid>
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    var textbox = new TextBox() {Text="hello",Width=500,Height=100 };
    root.Children.Add(textbox);
    RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
    await renderTargetBitmap.RenderAsync(textbox, 500, 100);
    img.Source = renderTargetBitmap;
    root.Children.Remove(textbox);
}