Adding children on the stack does not work programmatically

Can anyone spot the mistake I'm making?

Here is the code:

StackPanel stackPanel = new StackPanel(); stackPanel.Orientation = Orientation.Vertical; for (int index = _elements.Count - 1; index >= 0; index--) { FrameworkElement element = _elements[index]; WriteableBitmap tempBitmap = new WriteableBitmap(element, null); Image image = new Image(); image.Source = tempBitmap; stackPanel.Children.Add(image); } stackPanel.UpdateLayout(); _bitmap = new WriteableBitmap(stackPanel, null); _bitmap.Invalidate(); 

As you can see, I create a temporary image and then add it on the stack and then create the final WriteableBitmap file. Myy The first child from the stack has a height of 154, and the second - 389. After this line:

  _bitmap.Invalidate(); 

when I see PixelHeight it's only 389. Where did my first child go?

+6
source share
3 answers

Although both answers given by sLedgem and bathineni are correct, this does not seem to fit my situation. Also why do I want to add them to the layout? If this is convenient for you, you can, but in my case I want them to be in 100% memory, because my helper class, used mainly for printing, had nothing to do with any of the UIElements present on the screen. In this case, obviously, I would not want to pass my LayoutRoot or any other group to my helper class to do this hack!

Request the Silverlight runtime to display items in memory. You need to call the “Dimension” and “Arrange”:

Thus, I usually missed:

 stackPanel.Measure(new Size(width, height)); stackPanel.Arrange(new Rect(0, 0, width, height)); 

before:

 _bitmap = new WriteableBitmap(stackPanel, null); 

And I can get rid of this line:

 stackPanel.UpdateLayout(); 

Hope this helps someone who comes into this thread and has the same problem as me where I cannot find the LayoutRoot in your helper class.

+2
source

stackPanel or any other panels will not be displayed until they are added to visulatree (any visual element). means .. if you added 100 elements to the stack, these 100 elements will not be generated until the glass panel is visually displayed on the screen.

if you do not want to display the stack panel on the screen, then add the stack panel and immediately remove it. it will make a stackpanel visualize its children ...

OR

Create a grid or glass panel in XAML that has a height and width of 1 pixel and add your glass panel to this grid or panel stack ... so it will not be visible on the screen and it will be displayed in the background ....

0
source

bathineni is right, you need to stack stack before taking a picture. I suggest allowing visualization of the frame, and then capturing the bitmap after rendering it

  CompositionTarget.Rendering += CompositionTarget_Rendering; } void CompositionTarget_Rendering(object sender, EventArgs e) { _bitmap = new WriteableBitmap(stackPanel, null); _bitmap.Invalidate(); } 
0
source

Source: https://habr.com/ru/post/905884/


All Articles