2
votes

Is it possible to define a UserControl within a ResourceDictionary, and then add it to a component within the same XAML file? Something like:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        etc.>
    <Window.Resources>
        <ResourceDictionary>
            <UserControl x:Key="MyCustomLabel">
                <Label Content="Foo"/>
                ...lots more here
            </UserControl> 
        </ResourceDictionary>        
    </Window.Resources>
    <Grid>
        <MyCustomLabel />  //This doesn't work
        <MyCustomLabel />
        <MyCustomLabel />
    </Grid>
</Window>

I could define it in its own file, but I really only need it as a subcomponent within this file. I'd use a Style, but I don't know of a way to style the content of each row of my Grid. Any ideas?

1
What does your CustomLabel do? How is it different from a regular Label? Why is Style TargetType="Label" not a solution?Federico Berasategui

1 Answers

4
votes

You can achieve this with a DataTemplate resource and a ContentPresenter control. Here is an example which works analogously with your UserControl:

<Window>

    <Window.Resources>
        <DataTemplate x:Key="ButtonTemplate">
            <Button Content="{Binding}"/>
        </DataTemplate>            
    </Window.Resources>


    <StackPanel Margin="35">
        <ContentControl ContentTemplate="{StaticResource ButtonTemplate}" Content="Hallo" />
        <ContentControl ContentTemplate="{StaticResource ButtonTemplate}" Content="123" />
        <ContentControl ContentTemplate="{StaticResource ButtonTemplate}" Content="ABC" />
    </StackPanel>

</Window>

The ContentControls render as:

Rendered

Just replace Button with your own control and it should do what you want...