2013-04-15 32 views
2

是否可以在ResourceDictionary中定义UserControl,然后将其添加到同一个XAML文件中的组件?喜欢的东西:在ResourceDictionary中定义UserControl?

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

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

+0

你的CustomLabel做了什么?它和普通的'Label'有什么不同?为什么'Style TargetType =“Label”'不是解决方案? –

回答

4

您可以通过DataTemplate资源和ContentPresenter控件实现此目的。这里是一个与你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> 

ContentControls呈现为:

Rendered

刚刚与自己的控制代替Button,它应该做你想要的...

+0

正是我在找的东西!谢谢。 –

相关问题