Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 943
Ignacio Soler Garcia Avatar asked Jan 24 '12 23:01

Ignacio Soler Garcia


2 Answers

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...

like image 191
Cameron Peters Avatar answered Oct 15 '22 09:10

Cameron Peters


You can link all of your Margin properties by referring to a "Thickness" defined in your resources. I just did this in a project...

<!-- somwhere in a resource--> <Thickness  x:Key="CommonMargin" Left="0" Right="14" Top="6" Bottom="0" />  <!-- Inside of a Style --> <Style TargetType="{x:Type Control}" x:Key="MyStyle">      <Setter Property="Margin" Value="{StaticResource CommonMargin}" /> </Style> <!-- Then call the style in a control --> <Button Style="{StaticResource MyStyle}" />  <!-- Or directly on a Control --> <Button Margin="{StaticResource CommonMargin}" /> 

The key for me was figuring out that Margin was defined by "Thickness". Let me know if that's clear enough or if you need me to put it in a fully working XAML example.

like image 41
Rob Avatar answered Oct 15 '22 10:10

Rob