Change appearance of a control if the windows is maximized in WPF

Yesterday I was presented with an interesting question:

How can I design a user control that change appearance when the windows containing it is maximized?

Thanks to WPF binding and Triggers the solution is simple, suppose you want to create a border control that change thickness when the windows that contains this User Control is maximized, here is the code.

 <Border BorderBrush="Black"
                <Style TargetType="Border">
                    <Setter Property="BorderThickness" Value="1" />
                        <DataTrigger Binding="{Binding 
                                RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, 
                            <Setter Property="BorderThickness" Value="10" />

The solution is using a simple style that determines the value for the BorderThickness property of the Border Control. The key part is that I did not set an explicit value for BorderThickness in declaration of the control, but only in the style. This is necessary because value set at control level has higher priority than the style. The real power of WPF binding permits you to bind to RelativeSource with FindAncestor where Type is a Window. That specific binding is really useful in a UserControl, because you cannot know any property name of containers, but it is easy to find the first ancestor of type Window. Then you can simply create the trigger with this specific binding and change the property BorderThickness of the Border to 10 when the windows containing the user control gets maximized.

Gian Maria.

Published by

Ricci Gian Maria

.Net programmer, User group and community enthusiast, programmer - aspiring architect - and guitar player :). Visual Studio ALM MVP

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.