WPF UserControl inside another UserControl

I want to set the UserControl as the Content another UserControl in XAML, just as you can set Button's Content to anything.

Let's say my β€œexternal” UserControl looks like this:

 <MyUserControl> <Grid> <Border FancyPantsStyling="True"> <-- I want to insert other controls here --> </Border> </Grid> </MyUserControl> 

And I would like to create an instance this way:

 <local:MyUserControl> <local:MyUserControl.Content> <local:AnotherControl /> </local:MyUserControl.Content> </local:MyUserControl> 

How do I create a MyUserControl to render Content in a specific place?

+6
wpf user-controls
source share
2 answers

All you put in your UserControl XAML is its contents, so you cannot enter anything else by setting the Content property. There are several ways you could handle it. If you have nothing in the code for MyUserControl, you can just get rid of it and use something like:

 <ContentControl> <ContentControl.Template> <ControlTemplate TargetType="{x:Type ContentControl}"> <Grid> <Border FancyPantsStyling="True"> <ContentPresenter/> </Border> </Grid> </ControlTemplate> </ContentControl.Template> <local:AnotherControl/> </ContentControl> 

If you have code that does not have direct access to XAML elements, you can do a similar thing with an existing control (since UC comes from ContentControl):

 <local:MyUserControl> <local:MyUserControl.Template> <ControlTemplate TargetType="{x:Type local:MyUserControl}"> <Grid> <Border FancyPantsStyling="True"> <ContentPresenter/> </Border> </Grid> </ControlTemplate> </local:MyUserControl.Template> </local:MyUserControl> 

If you need to preserve the existing content associated with your code, you can use the DataTemplate to transfer in external content (to the new DP on MyUserControl) and apply this template to the ContentControl in UC XAML.

+4
source share

If I do not understand this question, you can use it under your control and configure its contents for everything you need.

0
source share

All Articles