WPF: Custom control layout - wpf

I'm working on a custom control in WPF that implements OnRender by calling a visit function with itself as the visitor. The control implements the visitor interface that draws lines, circles, etc. as appropriate. There are no child controls.
This all works, when the control renders I can see the primitives being rendered from my OnRender call.
However, what I'm struggling with is controlling the layout resulting from this. The Image control does exactly what I want to do. How do I replicate that behavior? Specifically:
If the user does not specify width or height, I want to set the rendered width/height of the control (either in my constructor or from another function that controls the layout).
If the user sets width or height to a specific value, I want to transform my drawing such that the aspect ratio of the control and drawing is preserved.
I'm trying to use the MeasureOverride functions to implement the behavior I want, but I'm not getting any results. My control is laid out with zero width/height, and then all my drawings get drawn on top of neighboring controls. Here is what I'm trying so far, hopefully this illustrates what I'm attempting to do:
protected override Size MeasureOverride(Size constraint)
{
SymbolLayout symbol = new SymbolLayout(this);
component.LayoutSymbol(symbol);
Point b1 = MapToPoint(symbol.LowerBound);
Point b2 = MapToPoint(symbol.UpperBound);
return new Size(b2.X - b1.X, b2.Y - b1.Y);
}
I'm not even sure that MeasureOverride is the right function to be using to accomplish this...

You also need to override the ArrangeOverride method. Layout in WPF is performed by a pair of recursive operations, Measure and Arrange. Measuring simply asks the visual tree what the required size of all the child controls is. This is done recursively, so if you had child controls, you would need to call Measure on all of your child elements as part of your Measure Override. Arranging is the second step in which the framework tells the control how much space it actually gets. Like Measuring, this is done recursively, and normally requires calling Arrange for each child control if there are any.

Related

MeasureOverride and ArrangeOverride. What is really AvailableSize/DesiredSize?

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.

How do you have a panel `ClipToBounds` without clipping children?

I have a custom Panel implementation that renders objects relative to a physical space (think like a floor plan). The panel allows the following actions:
Zoom in/out
Pan up/down/left/right
and more that isn't relevant to this question
The panel lives in with several other elements on screen, and I need to make sure the custom panel's graphics don't spill over the navigation and other controls.
The problem is this:
If the panel is set to clip, it clips the children before arranging them.
Let's say I have a circle in the floor plan and the user zooms in enough to make the circle bigger than the parent control. The panel applies clipping to the circle as if it were placed dead center, then arranges the circle where it is supposed to be. The end result is that the circle no longer looks like a circle and I have gaps in the image.
I need the clipping to be applied after arranging the elements, or only applied to the overall image as compiled by the children. How can I do this?
It turns out I had the opposite problem of the question the OP had in his letter to Dr. WPF where ClipToBounds = "Maybe"
If I override the GetLayoutClip() method in my control and return null, I essentially turn off clipping for the element. However, since ClipToBounds is still true for my panel, the rendered item doesn't spill over the rest of the application.
In the base class for all items that will be added to my custom panel I have this:
protected override Geometry GetLayoutClip(Size layoutSlotSize)
{
return null;
}
In my case this is exactly what I want. I honestly want my layout clip to be based on the parent panel and not the child size (with no sense of location within the panel).

Rendered Size of FrameworkElement (inside ViewBox) changed

In WPF, is there a way to detect that the actual render size (measured in screen units) changed?
I have elements which contain a rendered bitmap. If these elements are placed inside a Viewbox (or some other control that deals with RenderTransforms), I want to render the bitmap in the actual size on screen, so that no interpolation is done.
The main idea is that I want to place some complex parts of the UI in bitmaps as these would otherwise (when drawed in retained mode) reduce the render framerate and UI responsivity, making the application a pain to use. As a side effect, I would like to draw the lines inside these controls with constant thickness, even if scaled.
One way would be to check the size on screen with every render pass (or in some given time interval), and if it changed redraw the bitmap. However, I would like to know if there is maybe a built-in way to achieve this.

is FrameworkElement rendered or not?

Is there a way to know is certain FrameworkElement was rendered to the screen. For example. I have two rectangles, and one overlap other. But I'm not sure about "how much" one overlap other.
So I need to know is user will see both rectangles, or will see only one, or will see one fully and one partially?
It all depends on what kind of parent container it is, if both rectangles are inside StackPanel then they will not, you have to either make a custom container or use canvas as parent of these rectangles.
Then you can get LocalToScreen or such similar methods to get their absolute positions compared to screen or top parent window and find out whether they overlap or not.

How to get controls in WPF to fill available space?

Some WPF controls (like the Button) seem to happily consume all the available space in its' container if you don't specify the height it is to have.
And some, like the ones I need to use right now, the (multiline) TextBox and the ListBox seem more worried about just taking the space necessary to fit their contents, and no more.
If you put these guys in a cell in a UniformGrid, they will expand to fit the available space. However, UniformGrid instances are not right for all situations. What if you have a grid with some rows set to a * height to divide the height between itself and other * rows? What if you have a StackPanel and you have a Label, a List and a Button, how can you get the list to take up all the space not eaten by the label and the button?
I would think this would really be a basic layout requirement, but I can't figure out how to get them to fill the space that they could (putting them in a DockPanel and setting it to fill also doesn't work, it seems, since the DockPanel only takes up the space needed by its' subcontrols).
A resizable GUI would be quite horrible if you had to play with Height, Width, MinHeight, MinWidth etc.
Can you bind your Height and Width properties to the grid cell you occupy? Or is there another way to do this?
There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:
HorizontalContentAlignment="Stretch"
... to force the contents of a control to stretch horizontally. Or you can say:
HorizontalAlignment="Stretch"
... to force the control itself to stretch horizontally to fill its parent.
Each control deriving from Panel implements distinct layout logic performed in Measure() and Arrange():
Measure() determines the size of the panel and each of its children
Arrange() determines the rectangle where each control renders
The last child of the DockPanel fills the remaining space. You can disable this behavior by setting the LastChild property to false.
The StackPanel asks each child for its desired size and then stacks them. The stack panel calls Measure() on each child, with an available size of Infinity and then uses the child's desired size.
A Grid occupies all available space, however, it will set each child to their desired size and then center them in the cell.
You can implement your own layout logic by deriving from Panel and then overriding MeasureOverride() and ArrangeOverride().
See this article for a simple example.
Well, I figured it out myself, right after posting, which is the most embarassing way. :)
It seems every member of a StackPanel will simply fill its minimum requested size.
In the DockPanel, I had docked things in the wrong order. If the TextBox or ListBox is the only docked item without an alignment, or if they are the last added, they WILL fill the remaining space as wanted.
I would love to see a more elegant method of handling this, but it will do.
Use the HorizontalAlignment and VerticalAlignment layout properties. They control how an element uses the space it has inside its parent when more room is available than it required by the element.
The width of a StackPanel, for example, will be as wide as the widest element it contains. So, all narrower elements have a bit of excess space. The alignment properties control what the child element does with the extra space.
The default value for both properties is Stretch, so the child element is stretched to fill all available space. Additional options include Left, Center and Right for HorizontalAlignment and Top, Center and Bottom for VerticalAlignment.
Use SizeChanged="OnSizeChanged" in your xaml and the set the sizes you want in the code behind.
private void OnSizeChanged(object sender, SizeChangedEventArgs e)
{
TheScrollViewer.Height = MainWin.Height - 100;
}
Long term it will be better for you.
When your manager comes along and asks "make that a bit bigger" you won't to spend the afternoon messing about with layout controls trying to get it to work. Also you won't have to explain WHY you spent the afternoon trying to make it work.

Resources