DirtyNative
DirtyNative

Reputation: 2834

WPF Stackpanel spacing between custom controls

how is it possible to get a space between some custom controls inside a stackpanel? I did it right before with a Textbox, Button, and so on, but i cannot do it with a custom control.

That's the code i've got so far

<Grid>
    <StackPanel x:Name="spTasks" CanVerticallyScroll="True">
        <StackPanel.Resources>
            <Style TargetType="local:SmartTaskOverview">
                <Setter Property="Margin" Value="50,50,50,50" />
            </Style>
        </StackPanel.Resources>
    </StackPanel>

</Grid>

Thanks for your help

Upvotes: 0

Views: 567

Answers (1)

Brian Reichle
Brian Reichle

Reputation: 2856

FrameworkElements and their sub-classes don't just look for a resource using the controls type, they use the value of DefaultStyleKey. It's common practice for most sub-classes of Control (and some other FrameworkElements) to override the default value of this dependency property in the static constructor to be the type of the control, but sub-classes of UserControl usually don't bother.

static Foo()
{
    DefaultStyleKeyProperty.OverrideMetadata(typeof(Foo), new FrameworkPropertyMetadata(typeof(Foor));
}

If you didn't do this in your SmartTaskOverview then it will be looking for its default style using typeof(UserControl) as the resource key and not typeof(SmartTaskOverview).

Note: The UserControl will require a control template to show its children, this is normally provided by the default style for UserControl but by changing the key it will find your default style instead. To resolve this, just base your style on the UserControl style.

<Style TargetType="local:SmartTaskOverview" BasedOn="{StaticResource {x:Type UserControl}}">
    <Setter Property="Margin" Value="50,50,50,50" />
</Style>

Alternatively you could provide a simple template yourself.

<Style TargetType="local:SmartTaskOverview">
    <Setter Property="Margin" Value="50,50,50,50" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type local:SmartTaskOverview}">
                <ContentPresenter />
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Upvotes: 2

Related Questions