Przemek Marcinkiewicz
Przemek Marcinkiewicz

Reputation: 1305

StackPanel with User Controls in another User Control in Xaml Windows Phone

How Can I add child items to StackPanel in UserControl from C# code? Should I create something like DependencyProperty for it?

As it is easy to set Properties like Text for TextBlock in my UserControl, I have no idea how can I add items to StackPanel when using CodeBehind to do it dynamicaly.

Upvotes: 0

Views: 567

Answers (2)

Kulasangar
Kulasangar

Reputation: 9434

Yes you can do something like this (this is just a sample):

TextBlock printTextBlock = new TextBlock();
printTextBlock.Text = "Hello, World!";
//MainStackPanel below is the name given to your control in xaml
MainStackPanel.Children.Add(printTextBlock);

Sources:

Upvotes: 0

Sheridan
Sheridan

Reputation: 69959

StackPanel are only meant to be used for the most basic layout situations. It is far better using some kind of ListBox or ItemsControl depending on your requirements. You could add a collection DependencyProperty to your UserControl and do something like this:

In UserControl:

<ItemsControl ItemsSource="{Binding YourCollectionDependencyProperty, RelativeSource={
    RelativeSource AncestorType={x:Type YourPrefix:YourUserControl}}}" ... />

Then you could data bind another collection property to the UserControl from outside the control:

Outside UserControl:

<YourPrefix:YourUserControl YourCollectionDependencyProperty="{Binding Items}" ... />

Then adding new items to be displayed in the UserControl is as simple as adding items to the Items collection:

Items.Add(someNewObject);

Please read the Data Binding Overview page on MSDN for further information on data binding.

Upvotes: 1

Related Questions