SkyDancer
SkyDancer

Reputation: 159

How to create UserControl which may contain other elements in C#/WPF

I want to create a UserControl (like ItemsControl) which may contain more than one elemets inside it.

I want use this UserControl like this:

<local:MyUserControl Margin="10,34,10,10" Background="#FF202020">
    <local:OtherUserControl Background="#FF202020" SelectedBackground="#FF303030" />
    <local:OtherUserControl Background="#FF202020" SelectedBackground="#FF303030" />
    <local:OtherUserControl Background="#FF202020" SelectedBackground="#FF303030" />
    <local:OtherUserControl Background="#FF202020" SelectedBackground="#FF303030" />
    <local:OtherUserControl Background="#FF202020" SelectedBackground="#FF303030" />
</local:MyUserControl>

What should I write in XAML to make it works like I need? Can you give me any example of code?

Upvotes: 0

Views: 384

Answers (2)

T McKeown
T McKeown

Reputation: 12847

UserControls (in WPF) will render a single child, but that child (depending on what type of control you use) can have child items. For example, if you added a StackPanel to the user control the StackPanel could have multiple children.

All controls in WPF will render a single child unless the control is a Layout control like Grid, StackPanel, Canvas, DockPanel etc...

Here's another example using a StackPanel:

<UserControl x:Class="Drawing.Views.BidForm"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
        >
  <StackPanel>
     <Label FontWeight="Bold" HorizontalContentAlignment="Center"  > Item1</Label>
     <Label FontWeight="Bold"  HorizontalContentAlignment="Center"  >Item2</Label>
   </StackPanel>
</UserControl>

Upvotes: 0

Smolakian
Smolakian

Reputation: 414

You need to derive your control from ItemsControl. UserControl only provides a single Content element.

Alternatively, your UserControl could expose layout elements to which you could bind your other controls to their Content.

Upvotes: 0

Related Questions