2013-04-15 30 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

正是我在找的東西!謝謝。 –

相關問題