Search code examples
wpfwindowcontrolsmargin

How to set a default Margin for all the controls on all my WPF windows?


I want to set a default Margin of 3 on all the controls I put on all my windows and be able to override this value just on a really few number of items.

I've seen some approaches like doing styles but then I need to style everything, I would prefer something than can be done for all the controls together. I've seen other things like the MarginSetter but looks like it does not traverse subpanels. I want the Margin only on the controls I put at the window, nothing to do with the borders or other things of the visual tree.

Looks something pretty basic to me. Any ideas?

Thanks in advance.


Solution

  • The only solution I can find is to apply the style to each of the controls you are using on the window (I know that's not quite what you want). If you're only using a few different control types it's not too onerous to do something like this:

    <Window x:Class="WpfApplication7.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="350" Width="525">
        <Window.Resources>
            <!-- One style for each *type* of control on the window -->
            <Style TargetType="TextBox">
                <Setter Property="Margin" Value="10"/>
            </Style>
            <Style TargetType="TextBlock">
                <Setter Property="Margin" Value="10"/>
            </Style>
        </Window.Resources>
        <StackPanel>
            <TextBox Text="TextBox"/>
            <TextBlock Text="TextBlock"/>
        </StackPanel>
    </Window>
    

    Good luck...