Search code examples
data-bindingsilverlight-4.0stackpanel

Add controls to Stackpanel at runtime (SL 4.0)


I have a user control that contains a stackpanel.

I'm trying to find a way to bind the children of the stackpanel to aproperty so that I can access them from another control

Anyone has any clue how to do that?


Solution

  • If you are using DataBinding, then enable a binding override your stackpanel with an itemsControl. Then you can work with the collection property named ItemsProperty

    <StackPanel>
       <ItemsControl x:Name="itemsControl" ItemsSource="{Binding ItemsProperty, Mode=TwoWay}" >
              <ItemsControl.ItemTemplate>
                  <DataTemplate>
                     <ContentPresenter Content="{Binding}" /> <!-- you could also use Border -->
                  </DataTemplate>
             </ItemsControl.ItemTemplate>
        </ItemsControl>
    </StackPanel>
    

    If you are in the codebehind, you don't need to override the ItemsControl, just call stackpanel1.Children.Add(item); (if x:Name="stackpanel1" in XAML).

    Then stackPanel1.Children should have elements.