两个DataTemplates有没有办法共享一些元素?

时间:2022-05-22 19:37:18

Something like a template or base DataTemplate which both DataTemplates extend or inherit so I don't have to duplicate XAML.

类似于DataTemplate扩展或继承的模板或基础DataTemplate,所以我不必复制XAML。

2 个解决方案

#1


0  

What about UserControls? Create a base UserControl and then extend the second one?

UserControls怎么样?创建一个基本UserControl,然后扩展第二个?

<DataTemplate>
  <local:MyBase />
</DataTemplate>

And extend it like this?

并像这样扩展它?

<DataTemplate>
  <local:MyBase />
  <local:SomeOtherStuff />
</DateTemplate>

#2


0  

You can nest DataTemplates. Here an is example

您可以嵌套DataTemplates。这是一个例子

<DataTemplate x:Key="InnerTemplate">
    <TextBlock Text="{Binding}" Foreground="Purple" />
</DataTemplate>

<DataTemplate x:Key="OuterTemplate">
    <StackPanel>
        <TextBlock Text="Header" Foreground="Red" />
        <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource InnerTemplate}" />
    </StackPanel>
</DataTemplate>

In this case I just have a List bound to a listbox, and its itemtemplate set to the OuterTemplate template.

在这种情况下,我只有一个列表绑定到列表框,其itemtemplate设置为OuterTemplate模板。

<ListBox x:Name="_lbTest" Grid.Row="1" ItemTemplate="{StaticResource OuterTemplate}" ></ListBox>

#1


0  

What about UserControls? Create a base UserControl and then extend the second one?

UserControls怎么样?创建一个基本UserControl,然后扩展第二个?

<DataTemplate>
  <local:MyBase />
</DataTemplate>

And extend it like this?

并像这样扩展它?

<DataTemplate>
  <local:MyBase />
  <local:SomeOtherStuff />
</DateTemplate>

#2


0  

You can nest DataTemplates. Here an is example

您可以嵌套DataTemplates。这是一个例子

<DataTemplate x:Key="InnerTemplate">
    <TextBlock Text="{Binding}" Foreground="Purple" />
</DataTemplate>

<DataTemplate x:Key="OuterTemplate">
    <StackPanel>
        <TextBlock Text="Header" Foreground="Red" />
        <ContentPresenter Content="{Binding}" ContentTemplate="{StaticResource InnerTemplate}" />
    </StackPanel>
</DataTemplate>

In this case I just have a List bound to a listbox, and its itemtemplate set to the OuterTemplate template.

在这种情况下,我只有一个列表绑定到列表框,其itemtemplate设置为OuterTemplate模板。

<ListBox x:Name="_lbTest" Grid.Row="1" ItemTemplate="{StaticResource OuterTemplate}" ></ListBox>