0

Is it possible to create and render a UI Xaml control independently of a page?

Take the example of a UWP unit test...

    [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;
    }

This example throws following exception upon calling RenderAsync:

System.ArgumentException: Value does not fall within the expected range.

Star
  • 3,222
  • 5
  • 32
  • 48
Johnny Haddock
  • 415
  • 3
  • 11
  • Googling "create uwp control programmatically" gives lots of possibilities - including this as the first result : https://stackoverflow.com/questions/42306705/programmatically-add-buttons-to-a-uwp-app – PaulF Jan 03 '18 at 14:15
  • I think he wants to obtain the Rendered Image of the Control. – Tony Jan 03 '18 at 14:16
  • Yeah, created *and* rendered. – Johnny Haddock Jan 03 '18 at 14:17
  • How about something like this? https://stackoverflow.com/questions/5189139/how-to-render-a-wpf-usercontrol-to-a-bitmap-without-creating-a-window – Oystein Jan 03 '18 at 14:33
  • Yeah I tried that by adding... text.Measure(new Size(300, 300)); text.Arrange(new Rect(0, 0, 300, 300)); text.UpdateLayout(); but it doesn't help. – Johnny Haddock Jan 03 '18 at 14:40

1 Answers1

1

If you want to use RenderAsync method to render a snapshot of a UIElement, this UIElement should be in the visual tree. It means that you need to add it to the visual tree after you create it. See the following code sample:

<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);
}
Xie Steven
  • 8,544
  • 1
  • 9
  • 23