简体   繁体   中英

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?

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM