views:

31

answers:

1

My WPF UserControl contains two stack panels and each of them contains labels, text boxes and radio buttons.
I would like to set VerticalAlignment property to Center to all controls in my UserControl with as little code as possible.

Now I have 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 the controls on user control (this needs 3 style definitions, but automatically applies style to the control)

These three solutions need too much code.
Is there any other way to write this?
I hoped that defining style for FrameworkElement would automatically set property to all controls, but it does not work.

Here is snippet of my current XAML (I omitted 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's comment: I really hate idea of writing control formatting code in codebehind. XAML should be sufficient for this really simple user control.

Re Muad'Dib's comment: Controls I use in my user control are derived from FrameworkElement, so this is not an issue here.

+3  A: 

I had come across the same conundrum awhile ago as well. Not sure if this is the "best" way, but it was easy enough to manage by defining your base style and then creating separate styles for each control on the page that 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>
Metro Smurf
Yep, three lines more in resources, but less clutter in controls. Looks better than my current code.
zendar