Carlo
Carlo

Reputation: 25959

Sharing controls in ResourceDictionary

I have a grid that I want to share in several places, the grid has several controls (textboxes, labels, textblocks and buttons). I placed it in my ResourceDictionary like so:

<Grid Background="LightGray" x:Key="gridShare">
   <!-- other controls here -->
</Grid>

But when I use it in more than one place I get an exception saying:

"Specified element is already the logical child of another element. Disconnect it first."

Which makes sense, so I'm wondering if there's any other way to achieve this.

Thanks in advance.

Upvotes: 0

Views: 102

Answers (2)

Ed Bayiates
Ed Bayiates

Reputation: 11210

What you want to do is create a custom control with this as a template, then use an instance of this custom control instead of the Grid itself. Alternately create a UserControl and use instances of it.

Upvotes: 1

Dan J
Dan J

Reputation: 16708

If I correctly understand what you're trying to do (present the exact same composite control in multiple places), you can put the grid in a ControlTemplate and apply it to ContentControls:

In the ResourceDictionary:

<ControlTemplate x:Key="frequentlyUsedTemplate">
  <Grid>
    [...]
  </Grid>
</ControlTemplate>

In a UserControl:

<ContentControl Content="[...]" Template="{StaticResource frequentlyUsedTemplate}"/>

Upvotes: 3

Related Questions