I have a paginator for visuals. The problem is that when i create the visual from code i have to call Measure and Arrange. But i want to give them infinity value.
stackpanel.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
stackpanel.Arrange(new Rect(new Size(double.PositiveInfinity, double.PositiveInfinity)));
This causes
Cannot call Arrange on a UIElement with infinite size or NaN. Parent
of type 'System.Windows.Controls.StackPanel' invokes the UIElement.
Arrange called on element of type
'System.Windows.Controls.StackPanel'.
In the Measure step, a parent asks its children how much space they desire given a certain amount of space. This amount of space can also be infinity, which would mean to ask the children 'how much space would you like? There is no limit.'
In the Arrange step the elements are physically arranged on the layout. A parent tells its children where they are arranged and how much space they get. However the size parameter of the Arrange function cannot be infinity because this is the actual size the element will have.
Do you use Infinity because you want the visual occupy all the available space on printed page?
If yes what I usually do is that
Size sz = new Size(printCapabilities.PageImageableArea.ExtentWidth,
printCapabilities.PageImageableArea.ExtentHeight);
//update the layout of the visual to the printer page size.
yourElement.Measure(sz);
yourElement.Arrange(new Rect(new Point(printCapabilities.PageImageableArea.OriginWidth, printCapabilities.PageImageableArea.OriginHeight), sz));
Related
I've been stuck for two days trying to understand the layout principles of WPF.
I have read a bunch of articles and explored the wpf source code.
I know that measure/measureoverride method accepts a availablesize and then sets the DesiredSize property.
This makes sense. It recursively calls to the children and ask them to set their respective desired size.
There are two things (at least) I don't understand. Let us consider a WrapPanel.
Looking at the WPF source code, the MeasureOverride() method accepts an availablesize and then passes this to all the children. It then returns the largest width and largest height of the resulting desiredsize properties in the children. Shouldn't it divide the available space between the children? I would think that it would iterate over the children and then measure the first, then subtract the resulting desiredsize from the total availablesize so that the next child had less space to occupy. As I read the WPF, WrapPanel.MeasureOverride does not appear to set a desiredsize that it would need to fit all the children. It just gives the DesiredSize that any ONE of the children will fit in to.
Due to the nature of the wrappanel, I would expect that for a vertically oriented stackpanel a restriction in height would result in a wider DesiredSize (to fit more columns). Since a restriction in height affects the desired size of a wrap panel, doesn't this logic then belong in the MeasureOverride method? Why is the stacking then only reflected in the ArrangeOverride method?
I think I have some fundamental misunderstanding about the mechanics of these two method.
Can anybody give me a verbal description of DesiredSize and/or AvailableSize that makes this implementation make sense?
How to properly implement MeasureOverride and ArrangeOverride?
As I think this is the actual question you're asking, I will try to give you as much as I know about this topic.
Before we begin, you may want to start with reading Measuring and Arranging Children on MS Docs. It gives you a general idea of how the layout process works, although it doesn't really offer any information on how you should actually implement MeasureOverride and ArrangeOverride.
Note: For the sake of brevity, from here on out, whenever I say "control", I really mean "any class deriving from FrameworkElement".
1. What are the components that affect control's layout?
It is important to be aware that there are numerous parameters that affect the size and arrangement of a control:
Contents (i.e. child controls)
Explicit width and height
Margins
Horizontal and vertical alignment
Layout transform
Layout rounding
Something else I might have overlooked
Luckily, the only component we need to worry about when implementing custom layout, are child controls. This is because the other components are common to all controls, and are handled by the framework completely outside of MeasureOverride and ArrangeOverride. And by completely outside I mean that both input and output are adjusted to account for those components.
In fact, if you inspect the FrameworkElement API, you'll notice that measurement procedure is split into MeasureCore and MeasureOverride, the former taking care of all the required corrections, and that in fact you never call them directly on the child controls - you call Measure(Size) which does all the magic. Same goes to ArrangeCore and ArrangeOverride.
2. How to implement MeasureOverride?
The purpose of measure phase in layout pass is to provide feedback to the parent control on the size that our control would like to be. You may think of it as a hypothetical question:
Given that much available space, what is the minimal space you need to accommodate all your contents?
It goes without saying that this is (usually) required to determine the size of the parent control - after all, we (usually) measure our child controls to determine the size of our control, don't we?
Input
From docs:
The available size that this element can give to child elements. Infinity can
be specified as a value to indicate that the element will size to whatever content
is available.
The availableSize parameter tells us how much space do we have at our disposal. Be aware though that this might be an arbitrary value (including infinite width and/or height), and you should not expect to be given the exact same amount of space upon arrangement phase. After all, the parent control may call Measure(Size) on our control many times with whatever parameters, and then completely ignore it in arrangement phase.
As mentioned before, this parameter is already pre-corrected. For example:
If parent control calls Measure(100x100), and our control has margin set to 20 (on each side), the value of availableSize will be 60x60.
If parent control calls Measure(100x100), and our control has width set to 200, the value of availableSize will be 200x100 (hopefully it will become clear why as you continue reading).
Output
From docs:
The size that this element determines it needs during layout, based on its calculations
of child element sizes.
The resulting desired size should be minimal size required to accommodate all contents. This value must have finite width and height. It typically is, but is not required to be, smaller than availableSize in either dimension.
This value affects the value of DesiredSize property, and affects the value of finalSize parameter of subsequent ArrangeOverride call.
Again, the returned value is subsequently adjusted, so we should not pay attention to anything but child controls when determining this value.
Relation to DesiredSize property value
Size returned by MeasureOverride affects, but not necessarily becomes the value of DesiredSize. The key thing here is that this property is not really intended to be used by the control itself, but rather is a way of communicating the desired size to parent control. Note that Measure does not return any value - parent control needs to access DesiredSize to know the result of the call. Because of that, its value is actually tailored to be viewed by parent control. In particular, it is guaranteed not to exceed the original size passed as parameter of Measure, regardless of the result of child's MeasureOverride.
You may ask "Why do we need this property? Couldn't we simply make Measure return the size?". This I think was done for optimization reasons:
Often we need to access child's desired size in ArrangeOverride, so calling Measure(Size) again would trigger redundant measure pass on child control (and its descendants).
It is possible to invalidate arrange without invalidating measure, which triggers layout pass skipping the measure phase and going straight to the arrange phase. For example, if we reorder controls in a StackPanel, the total size of the child controls does not change, only their arrangement.
Summary
This is how measure phase looks like from perspective of our control:
Parent control calls Measure(Size) on the control.
MeasureCore pre-corrects the provided size to account for margins etc.
MeasureOverride is called with adjusted availableSize.
We do our custom logic to determine the desired size of our control.
Resulting desired size is cached. It is later used to adjust the finalSize parameter of ArrangeOverride. More on that later.
The returned desired size is clipped not to exceed the availableSize.
Clipped desired size is post-corrected to account for margins etc. (step 2. is reverted).
Value from step 7. is set as value of DesiredSize.
Possibly this value is clipped again not to exceed the original size passed as Measure(Size) parameter, but I think that should already be guaranteed by step 6.
3. How to implement ArrangeOverride?
The purpose of arrange phase in layout pass is to position all child controls in relation to the control itself.
Input
From docs:
The final area within the parent that this element should use to arrange itself
and its children.
The finalSize parameter tells us how much space do we have to arrange child controls. We should treat it as final constraint (hence the name), and do not violate it.
Its value is affected by the size of rectangle passed as parameter to Arrange(Rect) by the parent control, but also, as mentioned, by the desired size returned from MeasureOverride. Specifically, it is the maximum of both in either dimension, the rule being that this size is guaranteed not to be smaller than the desired size (let me re-emphasize this pertains to the value returned from MeasureOverride and not the value of DesiredSize). See this comment for reference.
In the light of that, if we use the same logic we used for measurement, we do not need any extra precautions to ensure we'll not violate the constraint.
You may wonder why there's this discrepancy between DesiredSize and finalSize. Well, that's what clipping mechanism benefits from. Consider this - if clipping was disabled (e.g. Canvas), how would the framework render the "overflowed" contents unless they were properly arranged?
To be honest, I'm not sure what will happen if you violate the constraint. Personally, I would consider it a bug if you report a desired size and then are not able to fit in it.
Output
From docs:
The actual size used.
This is the frontier of my ignorance, where knowledge ends and speculation begins.
I'm not really sure how this value affects the whole layout (and rendering) process. I know this affects the value of RenderSize property - it becomes the initial value, which is later modified to account for clipping, rounding, etc. But I have no idea what practical implications it might have.
My personal take on this is that we had our chance to be finicky in MeasureOverride; now it's time put our words into actions. If we're told to arrange the contents within given size, that's exactly what we should do - arrange child controls within finalSize, not less, not more. We don't have to tightly cover the whole area with child controls, and there may be gaps, but these gaps are accounted for, and are part of our control.
Having said that, my recommendation would be to simply return finalSize, as if saying "That's what you instructed me to be, so that's what I am" to the parent control. This approach seems to be notoriously practiced in stock WPF controls, such as:
Border
Canvas
Decorator
DockPanel
Grid
StackPanel
VirtualizingStackPanel
WrapPanel
Possibly others...
4. Epilogue
I guess that's all I know on the subject, or at least all I can think of. I bet you dollars to donuts there's more to it, but I believe this should be enough to get you going and enable you to create some non-trivial layout logic.
Disclaimer
Provided information is merely my understanding of the WPF layout process, and is not guaranteed to be correct. It is combined from experience gathered over the years, some poking around the WPF .NET Core source code, and playing around with code in a good old "throw spaghetti at the wall and see what sticks" fashion.
#grx70 answer is great and amazingly detailed. However, there is much more to know about the WPF layouting system and I wrote a whole article about it on CodeProject: Deep Dive into WPF Layouting and Rendering
Here is an overview how Properties and overwriting of MeasureOverride(), ArrangeOverride() and OnRender() work together to produce and use DesiredSize and RenderSize (which is by the way the exactly same value like ActualHeight and ActuelWidth).
For a detailed description see the article.
For myself, It would be logic if MeasureOverride calculates the size of the FrameworkElement and ArrangeOverride just positions the child elements. But ArrangeOverride does not only arrange the child elements. It does also calculate the size of the FrameworkElement again which I do not understand. Why can't MeasureOverride calculate the final size and thats it?
Because your element is potentially not the only one on the screen.
Layout is not that simple. WPF has to work out the actual physical space it has to use, then calculate how much space each element wants, scale the requested amount if it can, then apply it. Additionally some elements may want to make changes based on the exact amount of space allocated.
This previous answer of mine gives it to you as an analogy.
If you implement your own Panel, with your own layout algorithm and in your ArrangeOverride() call
child.Arrange(rect1)
with rect1 being different than the child's DesiredSize then the system may arbitrarily decide to ignore rect1 size and use something different. I've seen DesiredSize being used, I'm not sure if it's always the case. I'd say that this is something resembling a bug :)
If rect1 is calculated in the MeasureOverride() pass of the Panel then a workaround for this behavior is to call Measure() on the child for a second time passing size of rect1, so DesiredSize of the child is recalculated before the Arrange() pass.
I've got a composite control consisting of a rectangle and a few dynamically created labels (dynamically, because during design time I don't know how many labels shall be displayed). The labels' positions (margins) are evaluated during run time by combining whole control size, additional collection passed through dependency property and by heights of labels themselves.
Unfortunately, I didn't came into deterministic way of determining label height before one was rendered. ActualWidth and ActualHeight are 0 before the labels are displayed, Width/Height is not set, because I wish the labels to size themselves basing on their contents, DesiredSize returns either 0, correct size or size exceeding the real label size (like 2 or 3 times), RenderSize returns either valid size or 0 and it is like first label returns valid size and second one - 0.0, without any noticeable reason.
I've tried calling Measure() on the labels with double.PositiveInfinity passed by only to reach situation, when DesiredSize was way bigger than expected (all labels have the same font and consist only of numbers, so they all shall have more less similar size, but first had ~16 pixels, second - ~36, though after the rendering, RenderSize was valid for both of them).
Is there a deterministic way to check desired control size, based only on its contents (not on alignment/margins) before it is rendered on screen?
You can use UpdateLayout to force a measure / layout pass. After invoking this method ActualWidth and ActualHeight will have the correct values.
I'm trying to build a simple panel that contains one child and will snap it to nearest grid sizes. I'm having a hard time figuring out how to do this by overriding MeasureOverride and ArrangeOverride.
Here's what I'm after: I want my panel to tell its owner that (a) it wants to be as large as possible, then (b) when it finds out what that size is, it will size itself and its child UIElement according to the nearest smaller snap point. So if we're snapping to 10's, and I can be in a region no bigger than 192x184, the panel will tell its parent container "my actual size is going to be 190x180". That way anything bordering my control will be able to align to its edges, as opposed to the potential space.
When I put my panel inside of a Grid, I get either 0 or PositiveInfinity (I forget) for the incoming size in the overrides, but what I need to know is "how big can my space actually get?" not infinities..
Part of the problem I think is what WPF considers magic values of PositiveInfinity and 0 for size. I need a way to say, via MeasureOverride "I can be as big as you will allow me" and in ArrangeOverride to actually size to the snapped size.
Or am I going about this the completely wrong way? Measuring and arranging looks very complicated, just from wandering around a little in the code for the standard panels in Reflector.
In the measure step, if WPF sends you infinity, you are supposed to tell it how big you want to be. If it sends 0, then there is literally no space for your layout. In the arrange step, you will be told how much space is available for layout, which is very likely to be different than the size you were given in the measure step. You can not return infinity in either step. The following code should accomplish what you are after (note that I am assuming a UIElement Child property):
protected overrride Size MeasureOverride(Size availableSize)
{
Child.Measure(availableSize);
return Child.DesiredSize;
}
protected override Size ArrangeOverride(Size finalSize)
{
int w = (((int)finalSize.Width) / SnapPrecision) * SnapPrecision;
int h = (((int)finalSize.Height) / SnapPrecision) * SnapPrecision;
Child.Arrange(new Rect(0, 0, w, h));
return new Size(w, h);
}
I'm trying to figure out how come WPF doesn't go crazy when I set a window to resize to its content and then set its content to take all the available space... Any idea?
There are two passes in the layout system - measure and arrange.
First in the measure pass each child is given a proposed available size, and this propagates down the tree. This sets each child's DesiredSize property.
In the next, arrange pass, the DesiredSize is taken into account, but the parent has the final word on how much actual available size it will give to a child, and the parent places each child accordingly, informing it of the actual size it gets, and so on down the tree.
Also, consider several imaginable corner cases:
The child demands double.Infinity desired size: explicitly not allowed, raises an exception
The child sets its HorizontalAlignment to "Stretch": the parent doesn't offer infinite actual size
Window set to SizeToConent, child set to "Stretch", no other constraint set:
Window first offers infinite measure size
Child demands the size measured by its children (text width, margins, etc) - not infinite size
Arrange: window sets its size to a system-defined minimum or as desired by child, whichever is greater (can't be infinite)
The child stretches to fit the size determined in previous step
It's not that difficult: if the window is set to stretch to match its content, then it doesn't have a static size, so it assumes default dimensions. Going down the visual tree, the control wants to stretch to fill the window -- it doesn't force any dimensions, but instead accepts whatever size the window has (the default one).
My guess is that elements always have a size (default one if none specified above them in the hierarchy) and the mention whether that size is fixed or negotiable.
I'm only guessing here, but it's just to prove that the situation is not as bad as it seems. With a good update strategy in place, the elements can adjust in relation to each other in a sane manner.