2

是否可以在 ResourceDictionary 中定义 UserControl,然后将其添加到同一 XAML 文件中的组件中?就像是:

<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>

我可以在它自己的文件中定义它,但我真的只需要它作为这个文件中的一个子组件。我会使用样式,但我不知道如何设置网格每一行内容的样式。有任何想法吗?

4

1 回答 1

4

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...

于 2013-04-15T16:57:14.180 回答