WPF UserControl not created when overriding MeasureOverride and ArrangeOverride

I have a UserControl that looks like this:

<UserControl MaxHeight="32" MaxWidth="32" MinHeight="25" MinWidth="25"> <DockPanel> <!-- some stuff --> </DockPanel> </UserControl> 

In addition to the min / max size limit, I want the control to always be drawn using Width = Height . Therefore, I override MeasureOverride and ArrangeOverride :

 protected override Size MeasureOverride(Size availableSize) { var resultSize = new Size(0, 0); ((UIElement)Content).Measure(availableSize); var sideLength = Math.Min(((UIElement)Content).DesiredSize.Width, ((UIElement)Content).DesiredSize.Height); resultSize.Width = sideLength; resultSize.Height = sideLength; return resultSize; } protected override Size ArrangeOverride(Size finalSize) { ((UIElement)Content).Arrange(new Rect(0, 0, finalSize.Width, finalSize.Height)); return finalSize; } 

I understand that I have to call Measure and Arrange for each child of a UserControl. Since the DocPanel is the only child of my UserControl and (in my opinion) is stored in the Content UserControl property, I just call Measure and Arrange on this Content property. However, UserControl is not displayed. What am I doing wrong?

+6
wpf user-controls
source share
1 answer

Depending on how you place your UserControl, the value returned from the measurement step may not be used. If you have a setting in a grid with star-shaped rows / columns or a DockPanel, then the final size may be completely different.

You will need to apply the same logic to the arrangement phase so that it effectively ignores any additional space that it gives.

The following code should work and a little cleaner:

 protected override Size MeasureOverride(Size availableSize) { var desiredSize = base.MeasureOverride(availableSize); var sideLength = Math.Min(desiredSize.Width, desiredSize.Height); desiredSize.Width = sideLength; desiredSize.Height = sideLength; return desiredSize; } protected override Size ArrangeOverride(Size finalSize) { var sideLength = Math.Min(this.DesiredSize.Width, this.DesiredSize.Height); return base.ArrangeOverride(new Size(sideLength, sideLength)); } 
+3
source share

All Articles