views:

34

answers:

2

I'm looking to set a UserControl to be the Content of another UserControl in XAML, in the same way you can set a Button's Content to be anything.

Let's say my "outer" UserControl looks like this:

<MyUserControl>
   <Grid>
      <Border FancyPantsStyling="True">

         <-- I want to insert other controls here -->

      </Border>
   </Grid>
</MyUserControl>

And I'd like to instantiate this way:

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

How do I design MyUserControl to render it's Content in a specific location?

A: 

unless i misunderstood the question, you can use in your control and set its content to whatever you need.

akonsu
+1  A: 

All the stuff you put into your UserControl's XAML is its Content so you can't inject something else by setting the Content property. There are a few different ways you could handle this. If you don't have anything in the code-behind 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 behind that doesn't access the XAML elements directly you can do a similar thing with your existing control (since UC derives 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 keep the existing content connected to your code-behind you can use a DataTemplate to pass in the external content (into a new DP on MyUserControl) and apply that template to a ContentControl in the UC's XAML.

John Bowen