如何在 WPF 中重用 XAML 标记? [英] How can I reuse XAML tags in WPF?

查看:28
本文介绍了如何在 WPF 中重用 XAML 标记?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以代替我复制 XAML 中的代码段来定义我可以链接到的内容.更具体地说,我所拥有的是:

I was wondering whether it was possible to instead of me copying pieces of code in XAML, to define something that I could link to. In more concrete terms, what I have is:

<Grid>

 // Definitions

 <Label Content="Name:" />
 <Label Content="Age:" Grid.Column="1"/>
 ...
 <Grid>

现在我想要像 <Content_in_grid=nice_labels> 这样的东西,它应该简单地复制这些标签.

and now I would like to have something like <Content_in_grid=nice_labels> and it should simply copy these labels.

注意:我不想要网格,因为这些是我想与不同属性绑定的一些标签.

Notice: I do not want the grid, because these are some labels that I would like to bind with different properties.

PS:也许换个角度看,想象一下我想用 WPF 创建一个文件属性比较程序.所以你可以想象我必须再次复制所有这些标签,如文件名、日期等静态标签,但为了可维护性,如果我想将文件名更改为文件,那么我将不得不搜索和替换而不是在一个中编辑它地点.

PS: maybe a different perspective, imagine I would like to create a file properties comparison program with WPF. So you can imagine that I have to copy all those labels such as Filename, Date etc. static labels again, but for maintainability, if I would like to change Filename to File then I would have to search and replace instead of editing it in one place.

提前致谢.

推荐答案

在资源中添加:

<Window.Resources>
    <DataTemplate x:Key="MyGrid">
        <Grid>
            <Label Content="Name:" />
            <Label Content="Age:" Grid.Column="1" />
        </Grid>
    </DataTemplate>
</Window.Resources>

然后在你想要的地方使用它:

And then use it where you want:

<StackPanel>
    <ContentPresenter ContentTemplate="{StaticResource MyGrid}" />
    <ContentPresenter ContentTemplate="{StaticResource MyGrid}" />
    <ContentPresenter ContentTemplate="{StaticResource MyGrid}" />
</StackPanel>

这篇关于如何在 WPF 中重用 XAML 标记?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆