WPF: find how much space a control needs - wpf

In my application I have an area in the main window that at any time can contain one of several different controls.
This controls are generated at runtime and their contents can vary depending on underlying data, so I do not know beforehand how much space they'll take up.
What I want to know is: is there a way to determine at runtime how much space a control needs in order not to be "cut off" or need a scroll? ie: how much space does it need to be COMPLETELY visible?
I tried the "DesiredSize" property and it kinda works, but not always: if the control has been used already (it has already a size) it returns it's last used size rather than the correct one, even if I call "InvalidateMeasure()".
Any ideas??

Call Measure on the control. Give it infinite space as the available size for the calculation. Then check the DesiredSize to get the needed width (and/or height).

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.

I want bigger pixbufs rendered onto GtkSourceGutter

It seems that the size of the source marks rendered with GtkSourceGutterRenderer are remotely tied up to the size of the text in the GtkSourceView. I want to have bigger pixbufs, without making the text font size bigger and to achieve that I concluded I have to subclass a widget and override its draw signal handler.
However I have no idea which widget to subclass on. Surely one of you knows?
I think it's probably GtkSourceGutterRendererPixbuf itself that you have to subclass. If not that, then probably GtkSourceGutterRenderer with a lot of duplicated code from GtkSourceGutterRendererPixbuf.

Distribute text top-to-bottom instead of left-to-right

I'm working on a view that's implementing a multi-column text layout using CoreText (using CTFramesetter).
CoreText usually fills each frame completely, so when I call CTFramesetterCreateFrame with three rects that make up my columns, I get a layout that's similar to the following image:
So the left column is filled completely, the middle column partially and the right column is empty. But instead, I'd like the text to distribute over the three columns so that they take up the least vertical space possible, like in this image:
How to achieve this with CoreText?
I don't mind going low-level here, even drawing each CTRun by hand is an option if necessary.
One idea I came up with would be to create a large frame with the width of a column and then figure out which CTLine to draw in which column. But this has a few limitations:
It would only work if all columns had the same width.
It does not work with clipping paths.
Unfortunately, I'll need to use clipping paths (as in kCTFrameClippingPathsAttributeName) so this idea is out. I could live the fixed column width limitation, though.
Another idea would be to reduce the height until the last frame overflows but that's a pretty brute-force way that surely wastes resources.
(BTW, due to compability requirements the use of TextKit classes like NSTextStorage isn't possible; the resulting view is intended to be used on Mac and iOS, but it needs to work on iOS < 7)
Since there doesn't seem to be a non-expensive way to solve this, here's how I've done it:
I did go with the "reduce the height until the last frame overflows" approach. To reduce the height, I simply have another clipping path (kCTFrameClippingPathsAttributeName) which is a rectangle that fills the bottom of the view to the required height.
The probably most expensive but simple way would have been to increase the rectangle height until finally the text doesn't fit inside the last frame any more.
Instead I've implemented a binary search for that. For my demo app, I usually find the correct height after 8-10 recursions which still is expensive but at least it's pixel-perfect and doesn't rely on any other information other than "did the last frame overflow".

Increasing the size of a WPF application

I've just created my first WPF application (3 calculators inside 3 different tabs).
The entire application has been built using widths/margins/paddings as static values, since I originally didn't know that dynamic values can be used by just putting an asterix after the value.
The client has come back to me though and has asked me to increase the size of the app, that includes form fields, tabs, font-sizes, grids etc...
What would be the easiest (and/or quickest) way to do this? I'd hate to go value by value resizing every single element since there are quite a few.
I can provide code but there is lots of it and I'm not sure of how much help it would be.
Appreciate your help,
Marko
Put it all in one ViewBox, play with viewbox size to change the app size
Write an XSLT transform to take your XAML as input and spit out appropriate modified XAML, which you put back in your app.

Why isn't always possible to set a winforms dimensions?

I'm trying to size a checkboxlist control to 500,250 from its current 502,251 (It's an OCD thing) but every time I try, it just reverts to 502,251.
Is it because the parent container is docked in the window? Are there any workarounds?
(This is through the visual designer)
Most likely the control is being resized due to the control's font size. The ListControl does not like to display an item that will be "split" by the bottom edge, so it will resize the height. Try changing the control's font size and adjust again to verify.
No work around, and you really do not what one, because the control is really doing the right thing.
Yes, it is OCD. I have it also, but this one you have to let go. :O) Consider yourself lucky because you are only one or two pixels off. I was five pixels off once, and I had to put a note on my monitor to ignore it. It so bothered me.

Resources