0

I have a WPF that creates buttons dynamically when the form is loaded and adds them to a StackPanel that has been declared in XAML. I would like to define the style for these buttons completely in XAML inside the StackPanel.Resources. So far I am able to do this for Style properties just fine, but what I am having trouble figuring out is the best way to do the margin. I know that Margin is a Thickness and cannot actually be applied in a style, but must be defined as a static resource and applied directly to the Margin property. Is there a way I can do this in XAML without resorting to the code-behind?

Here is the XAML for my StackPanel:

        <StackPanel
            x:Name="_dialogButtons"
            Orientation="Horizontal"
            HorizontalAlignment="Right"
            DockPanel.Dock="Right">

            <StackPanel.Resources>
                <Style
                    TargetType="{x:Type Button}">
                    <Setter
                        Property="MinWidth"
                        Value="75" />
                    <Setter
                        Property="Padding"
                        Value="3" />
                </Style>                    
            </StackPanel.Resources>

        </StackPanel>

Thanks,

Mike

mclark1129
  • 7,532
  • 5
  • 48
  • 84
  • *"I know that Margin is a Thickness and cannot actually be applied in a style"* That's just not true. – H.B. May 31 '11 at 15:38
  • Yeesh, I was WAY off on that one. I'm not sure what I was thinking, I may have just been confused with a different issue I ran into in the past with a particular property that did not function the same way in styles that other properties did. – mclark1129 May 31 '11 at 16:13

3 Answers3

4

You state that "I know that Margin is a Thickness and cannot actually be applied in a style", this is not correct. Margins can be applied in XAML, the Thickness type has a type converter that can convert a string to a Thickness allowing you to define it as follows:

<setter Property="Margin" Value="5,5,5,5"/>
ColinE
  • 68,894
  • 15
  • 164
  • 232
4
<StackPanel.Resources>
    <Style
        TargetType="{x:Type Button}">
        <Setter
            Property="MinWidth"
            Value="75" />
        <Setter
            Property="Padding"
            Value="3" />
        <Setter
            Property="Margin"
            Value="3" />
    </Style>                    
</StackPanel.Resources>
tofutim
  • 22,664
  • 20
  • 87
  • 148
2

Padding is a Thickness as well, and it seems you could add that just fine ;).

So just do it the same way as Padding.

Arcturus
  • 26,677
  • 10
  • 92
  • 107