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
开发者_C百科Property="Padding"
Value="3" />
</Style>
</StackPanel.Resources>
</StackPanel>
Thanks,
Mike
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"/>
<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>
Padding
is a Thickness
as well, and it seems you could add that just fine ;).
So just do it the same way as Padding
.
精彩评论