gpt4 book ai didi

wpf - 如何复用控制模板?

转载 作者:行者123 更新时间:2023-12-03 20:22:46 26 4
gpt4 key购买 nike

我可以创建参数化控件模板,即创建可能包含不同控件的控件模板。例如,我可以使用带有标签或按钮的控制模板——在某个位置我想要的任何东西。

<ControlTemplate x:Key="MessageCTemplate">
<Grid …>
<Rectangle …/>
<Rectangle …/>
<Rectangle …/>

<!--I want to have here button, label or whatever I want-->
<label x:Name=”MsgLabel”>
<Grid/>

<Style x:Key="MsgStyle" TargetType="{x:Type Button}">
<Setter Property="Opacity" Value="0.6" />
<Setter Property="Template" Value="{StaticResource MessageCTemplate}" />
<Style/>

我不喜欢编写相同的控件模板,它们的代码中只有一个不同的字符串。或者,也许,我误解了某种东西,并且存在另一种避免复制过去的方法。

最佳答案

您所描述的是一个 ContentControl。这是许多常用控件的基类,包括 Button、Label、ListBoxItem...

ContentControl 的想法是它可以定义自己的布局和一些 UI 元素,还包括一个占位符,可以注入(inject)任何设置为其 Content 属性的内容。还有一个 HeaderedContentControl 允许 2 个占位符用于其他内容。

<ControlTemplate x:Key="MessageCTemplate" TargetType="{x:Type ContentControl}">
<Grid …>
<Rectangle …/>
<Rectangle …/>
<Rectangle …/>
<ContentPresenter/> <!-- This is where the content shows up -->
<Grid/>
</ControlTemplate>

<Button Template="{StaticResource MessageCTemplate}">
<Label Content="My label"/>
</Button>

<Button Template="{StaticResource MessageCTemplate}">
<Ellipse Fill="Orange" Width="100" Height="30"/>
</Button>

关于wpf - 如何复用控制模板?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3958216/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com