且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在WPF中的另一个数据模板中使用一个数据模板

更新时间:2023-01-07 09:37:49

如果XAML中有一些样板,则可以使用 ContenPresenter 作为宏。 ,以在多个地方扩展样板。首先,定义 DataTemplate ,然后使用 ContentPresenter 和资源键来扩展宏。下面是一个示例:

If you have some boilerplate in XAML, you can use ContenPresenter as a sort of "macro" to expand your boilerplate in multiple places. First you define a DataTemplate and then you use the ContentPresenter with the resource key to "expand" the macro. Here is an example:

<Grid>
    <Grid.Resources>
        <DataTemplate x:Key="boilerplate">
            <StackPanel Orientation="Horizontal">
                <Rectangle Width="100" Height="100" Stroke="Black" Fill="{Binding}"/>
                <Rectangle Width="100" Height="100" Stroke="Black" Fill="{Binding}"/>
            </StackPanel>
        </DataTemplate>
    </Grid.Resources>
    <StackPanel>
        <ContentPresenter ContentTemplate="{StaticResource boilerplate}" Content="Red"/>
        <ContentPresenter ContentTemplate="{StaticResource boilerplate}" Content="Blue"/>
    </StackPanel>
</Grid>

由于模板是真实的模板,因此可以使用数据绑定。可以将其视为仅包含一项的 ItemsControl 。如果没有绑定,则可以省略 Content 属性。您可以将其视为宏的参数。

As the template is a real template you can use data binding. Think of it as an ItemsControl with just one item. If there is no binding you can omit the Content property. You can think of it as the macro "parameter".

过度使用此选项将使您的XAML难以阅读,并且具有适度的性能成本,因此请谨慎使用。最后,存在一些局限性,因为宏总是扩展为一个***元素,因此您不能将两个元素添加到单个 Panel 中,而一次性使用 ContentPresenter

Over-using this will make your XAML harder to read and it has a modest performance cost so use it carefully. Finally, there are some limitations in that the "macro" always expands to one top-level element so you cannot add two elements to a single Panel with a single use of ContentPresenter.