I wanted a Custom Control that wraps around its child and adds a four FrameworkElements as (border sides), so I chose a WPF's Decorator Class, both the class and the xaml are in the following github gist. Decorator The Measurements and Arrangements are as expected, yet the child is always centered to the Decorator even when the its alignments are set.
I tried many things, yet they either ruin the arrangements/measurements or don't work at all, so maybe there is a fundamental problem with my understanding of MeasureOverride & ArrangeOverride or ???. I want this decorator to function like the Border Class yet has FrameworkElements as a border.
When extending a class like
Decoratorin WPF, understanding howMeasureOverrideandArrangeOverridework is crucial because they determine how the child elements are sized and positioned, respectively. In your implementation, you've overridden these two methods, which is correct, but the way you've handled the alignments and arrangement of the childFrameworkElementmay not be taking into account theHorizontalAlignmentandVerticalAlignmentproperties.To make your
BorderWrapperrespect the child'sHorizontalAlignmentandVerticalAlignmentproperties (like the standardBorderclass does), you need to adjust how you place the child inside theArrangeOverridemethod. TheArrangeOverrideshould account for the child's alignment relative to the available space, after allocating space for the "borders".Here's an adjusted version of your
ArrangeOverridecode snippet that aims to respect the child's alignment properties:In this modified version, we determine
childLeftandchildTopby considering the horizontal and vertical alignments of the child. TheHorizontalAlignmentandVerticalAlignmentof the child can beLeft,Center,RightorStretch(same for vertical alignment). If it'sCenter, we place the child in the middle of the available space, minus the space taken by the border sides. ForRightorBottom, we place it at the end of the available space.LeftandTopwill start from the border end, which is effectively0distance from the border.It's essential to remember that the default behavior for
HorizontalAlignmentandVerticalAlignmentisStretch. In that case, the control will stretch to fill the available space (minus the space taken by borders), which may make your borders seem non-effective if you don't actually have any space constraints on theBorderWrapper. For non-stretch alignments, this should position the child considering the space occupied by the borders and the chosen alignment.Make sure to test with different alignments and container sizes to ensure that your control behaves as expected in a variety of scenarios.