mclark1129
mclark1129

Reputation: 7592

Setting margin in XAML for dynamically created WPF controls

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

Upvotes: 0

Views: 3717

Answers (3)

tofutim
tofutim

Reputation: 23374

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

Upvotes: 4

ColinE
ColinE

Reputation: 70142

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"/>

Upvotes: 4

Arcturus
Arcturus

Reputation: 27055

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

So just do it the same way as Padding.

Upvotes: 2

Related Questions