18. October 2021 · Categories: .NET

In WPF/XAML, you will very often create your custom templates for containers, and one of the issues is to properly adjust the template contents with its container.

The most common problem is making the template fill the container completely. This is done with the properties HorizontalContentAlignment and VerticalContentAlignment of the container, setting them to Stretch. You can then use the Margin of your top level template element for positioning.

When we need more precise control, we can do calculations with a converter based on the actual layout parameters of the container. You get that info with a RelativeSource binding in FindAncestor mode.

This requires you to add a simple converter to your project to do the calculation:

and include it in your application resources