1

I have made a simple UserControl called SmallCtrl. Inside another UserControl called LargeCtrl, I dynamically add SmallCtrl to the list of its children using this code behind (for testing):

public void LargeCtrl_Loaded(object sender, EventArgs args)
{
     for (int i = 0; i < 10; i++)
         _StackPanel.Children.Add(new SmallCtrl());
}

I use StackPanel with horizontal orientation and I need its child UserControls to have a right margin to create space between them, here is the style resource:

    <Grid>
        <StackPanel x:Name="_StackPanel" Orientation="Horizontal">
    <StackPanel.Resources>
        <Style TargetType="{x:Type customCtrls:SmallCtrl}">
            <Setter Property="Margin" Value="0,0,10,0"/>
        </Style>
    </StackPanel.Resources>
</StackPanel>
    </Grid>

However, when I load my Window with LargeCtrl the margin doesn't show. If I replace my SmallCtrl with a TextBox, everything works. What is my problem here?

eYe
  • 1,695
  • 2
  • 29
  • 54
  • 1
    You have your implicit style set in `StackPanel.Resources`, so it will only apply to controls inside of _StackPanel. Is your LargeControl inside _StackPanel? – Rachel Apr 23 '15 at 19:38
  • My SmallCtrl is inside the _StackPanel while LargeCtrl contains the _StackPanel. I am trying to apply margin to SmallCtrl's only – eYe Apr 23 '15 at 19:42
  • 1
    Does it work if you call `Add(new SmallCtrl { Margin = new Thickness(0, 0, 10, 0) })`? – Clemens Apr 23 '15 at 19:57
  • Anyway, you should do this with an ItemsControl that has a horizontal StackPanel as ItemsPanel and SmallCtrl in its ItemTemplate. – Clemens Apr 23 '15 at 19:59
  • @Clemens if I do it that way it works perfectly! However, I need to get rid of any code behind (MVVM) – eYe Apr 23 '15 at 20:00
  • ItemsControl is the right approach. – Clemens Apr 23 '15 at 20:01
  • @Clemens maybe you're right but I am really curious what is the problem with my approach – eYe Apr 23 '15 at 20:28
  • 1
    If I remember correctly, [WPF considers a control template to be a boundry](http://stackoverflow.com/a/14503661/302677) and will not automatically apply implicit templates to them. I recall [running into this issue in the past](http://stackoverflow.com/q/9035878/302677), although I'm not positive if it's your exact case since I'm not sure the structure and properties of your controls. – Rachel Apr 23 '15 at 20:48

0 Answers0