Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
175
RenderTargetBitmap and XamChart - Broken
posted

I'm writing an application that has need of making small bitmaps of charts for static preview purposes. I've tried everything I can think of to get RenderTargetBitmap to work with XamChart, but all I get is an empty bitmap (the bitmap is the correct size, it's just filled with transparent pixels).  The following code demonstrates the use of RenderTargetBitmap with a regular button and a XamChart. Both are created at run time and are never displayed. Creating a bitmap of the button works, but not XamChart.  Is this a bug, or is there a workaround?

 

<Window x:Class="XamChartTest.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="XamChartTest" Height="300" Width="300"
    >
    <Grid>
      <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
      </Grid.RowDefinitions>
     
      <Button Content="XamChart Test" Click="OnClickChart" Grid.Row="0"/>
      <Button Content="Regular Test" Click="OnClickTest" Grid.Row="1" />
    </Grid>
</Window>

 

        public void OnClickChart(object sender, RoutedEventArgs e)
        {
            XamChart testChart = new XamChart();
            testChart.Width = 200;
            testChart.Height = 200;
            testChart.Measure(new Size(200, 200));
            testChart.Arrange(new Rect(0, 0, 200, 200));

            RenderTargetBitmap bmp = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(testChart);

            PngBitmapEncoder png = new PngBitmapEncoder();
            png.Frames.Add(BitmapFrame.Create(bmp));
            using (Stream stm = File.Create(@"C:\TestChart.png"))
                png.Save(stm);
        }

        public void OnClickTest(object sender, RoutedEventArgs e)
        {
            Button testButton = new Button();
            testButton.Content = "Test Button";
            testButton.Width = 200;
            testButton.Height = 200;
            testButton.Measure(new Size(200, 200));
            testButton.Arrange(new Rect(0, 0, 200, 200));

            RenderTargetBitmap bmp = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);
            bmp.Render(testButton);

            PngBitmapEncoder png = new PngBitmapEncoder();
            png.Frames.Add(BitmapFrame.Create(bmp));
            using (Stream stm = File.Create(@"C:\TestButton.png"))
                png.Save(stm);
        }