Setting the VerticalAlignment property for all controls

My WPF UserControl contains two stack panels, each of which contains shortcuts, text fields, and radio buttons.
I would like to set the VerticalAlignment property in Center to all controls in UserControl with a minimal amount of code.

Now I have the following solutions:

  • brute force - put VerticalAlignment="Center" in each control
  • define one style for FrameworkElement and apply it directly
  • Define styles for each type of control for a user control (this requires 3 style definitions, but automatically applies the style to the control)

These three solutions require too much code.
Is there any other way to write this?
I was hoping the style definition for FrameworkElement automatically set the property for all controls, but it does not work.

Here is a snippet of my current XAML (I missed a second, very similar stack panel):

 <UserControl.Resources> <Style x:Key="BaseStyle" TargetType="FrameworkElement"> <Setter Property="VerticalAlignment" Value="Center" /> </Style> </UserControl.Resources> <Grid> <StackPanel Orientation="Horizontal"> <TextBlock Style="{StaticResource BaseStyle}" Text="Value:" /> <RadioButton Style="{StaticResource BaseStyle}">Standard</RadioButton> <RadioButton Style="{StaticResource BaseStyle}">Other</RadioButton> <TextBox Style="{StaticResource BaseStyle}" Width="40"/> </StackPanel> </Grid> 

Edit:
Re Will comment: I really hate the idea of โ€‹โ€‹writing code formatting code in codebehind. XAML should be sufficient for this really simple user control.

Re Muad'Dib comment: The controls that I use in my user control are derived from FrameworkElement , so this is not a problem.

+6
layout styles wpf
source share
1 answer

I ran into the same riddle some time ago. I'm not sure if this is the โ€œbestโ€ way, but itโ€™s easy enough to control by defining your base style, and then creating separate styles for each control on the page inherited from the base style:

 <Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="500" Height="300" Background="OrangeRed"> <Page.Resources> <Style TargetType="FrameworkElement" x:Key="BaseStyle"> <Setter Property="VerticalAlignment" Value="Center" /> <Setter Property="Margin" Value="0,0,5,0" /> </Style> <Style TargetType="TextBlock" BasedOn="{StaticResource BaseStyle}" /> <Style TargetType="RadioButton" BasedOn="{StaticResource BaseStyle}" /> <Style TargetType="TextBox" BasedOn="{StaticResource BaseStyle}" /> </Page.Resources> <Grid> <StackPanel Orientation="Horizontal"> <TextBlock Text="Value:" /> <RadioButton>Standard</RadioButton> <RadioButton>Other</RadioButton> <TextBox Width="75"/> </StackPanel> </Grid> </Page> 
+9
source share

All Articles