I am trying to generate an image of some WPF elements in runtime on a web application. I have had moderate success but there is an issue where child elements will not stretch to fill their parents despite functioning normally if I use the same code in a WPF desktop application. Here’s the code:
Canvas imageCanvas = new Canvas { Width = 1651, Height = 2551, Background = Brushes.White };
Canvas Test = new Canvas();
System.Windows.Shapes.Path Path = new System.Windows.Shapes.Path();
Path.Data = Geometry.Parse("M 0,0 H 287 V 287 H 0 Z");
Path.Stretch = Stretch.Fill;
Path.Stroke = Brushes.Black;
Path.StrokeThickness = 1;
Test.Width = 500;
Test.Height = 500;
Test.Children.Add(Path);
imageCanvas.Children.Add(Test);
Canvas.SetTop(Test, 10);
Canvas.SetLeft(Test, 10);
// Update layout
Size size = new Size(imageCanvas.Width, imageCanvas.Height);
imageCanvas.Measure(size);
imageCanvas.Arrange(new Rect(size));
RenderTargetBitmap bitmapRenderer = new RenderTargetBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Pbgra32);
bitmapRenderer.Render(imageCanvas);
What I expect to see is the square filling up it’s parent canvas but this doesn’t happen. In fact the size of the parent seems to be completely ignored and the path is always the same. Is there anything I can do to force a resize? I thought that the measure and arrange calls on the topmost canvas would do this but apparently not. 🙁
this is a limitation of canvas, and the only way i know to overcome this is to put your Canvas in a “ViewBox” or variation of that, check out this link
http://msdn.microsoft.com/en-us/library/system.windows.controls.viewbox.aspx