Search code examples
c#wpfsizeuielement

Is there a way to set the Width and Height of a UIElement?


Is there a way to set the size of a UIElement (without casting to FrameworkElement), perhaps similar to how using RenderSize on a UIElement mirrors getting size information via ActualWidth & ActualHeight on a FrameworkElement)?

In effect, I guess you could say I want to set the RenderSize of a UIElement.

I'm thinking along the lines of an approach that would somehow enable me to force a measure / arrange pass with the desired size, but can't seem to find an appropriate point of attack.


Solution

  • The closest thing to a way of doing this is to call Arrange(finalRect) on the UIElement. If the element's ArrangeCore override (and/or subsequent OnRender) implementation "stretches" to / makes use of the whole area given (by finalRect), its size will be set accordingly. But only if.

    Personally, I decided to amputate WPF at its UI neck and build my own layout system and a complete set of UI controls that descend directly from UIElement. That way, I sidestep the whole problem, since the granddaddy in my hierarchy, the firstborn son of UIElement, has all the members necessary for layout built in from the getgo - including properties for Width and Height (and is basically therefore a sizable UIElement).

    The rest of my code then just deals with grandpa, i.e. my version of "FrameworkElement" (which is way more efficient - since it sheds all the context / dependency / styling functionality etc that I don't need anyway. WPF pays a price for being so generic).

    A FrameworkElementWrapper control is included in that family, should there be a need to include any conventional FrameworkElements in the layout.