Search code examples
wpfuser-controls

Creating a WPF user control with a child element


I try to create a "container" user control that can display UIElement objects as child in WPF. The usage of the control should look like this:

<general:DisplayContainer Title="Hello">
  <TextBlock x:Name="AnyUIElement" />
</general:DisplayContainer>

where the TextBlock is just an example. So far I created the UserControl and bind the Title property like this:

<Grid x:Name="Grid_Main">
  <Border x:Name="Border_Main" BorderThickness="2" Margin="10" CornerRadius="5" Padding="7" />

  <TextBlock x:Name="TextBlock_Title" Background="{Binding Background, ElementName=Grid_Main}" HorizontalAlignment="Left" VerticalAlignment="Top"  Text="{Binding Path=Title, FallbackValue=Title}" Margin="20,2,0,0" Padding="3,0" />
</Grid>

The Codebehind file looks like this:

public partial class DisplayContainer : UserControl
{
  public DisplayContainer()
  {
    InitializeComponent();
    this.DataContext = this;
  }

  public string Title
  {
    get { return (string)GetValue(TitleProperty); }
    set { SetValue(TitleProperty, value); }
  }

  public static readonly DependencyProperty TitleProperty =
      DependencyProperty.Register("Title",typeof(string), typeof(DisplayContainer));
}

Now, how can I modify my control in a way, that i accepts a child element in the XAML-file, when I use the control? The child should be displayed through the Border_Main.Child Property.

Thanks in advance,
Frank


Solution

  • Just set the UserControl's Template property

    <UserControl ...>
        <UserControl.Template>
            <ControlTemplate TargetType="UserControl">
                <StackPanel>
                    <TextBlock Text="{Binding Title,
                               RelativeSource={RelativeSource AncestorType=UserControl}}"/>
                    <ContentPresenter />
                </StackPanel>
            </ControlTemplate>
        </UserControl.Template>
    </UserControl>
    

    and put the displayed element in the UserControl's Content:

    <local:DisplayContainer Title="A Title">
        <TextBlock Text="Hello"/>
    </local:DisplayContainer>