将参数传递给模板
假设我定义了一个带圆角的按钮。
<Style x:Key="RoundButton" TargetType="Button">
<!-- bla bla -->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border CornerRadius="0,5,5,0" />
<!-- bla bla -->
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
该按钮的用户是否可以指定 CornerRadius? 我可以使用 TemplateBinding 吗? 但我应该绑定到哪里呢? (标记?)
Say I have defined a button with rounded corners.
<Style x:Key="RoundButton" TargetType="Button">
<!-- bla bla -->
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border CornerRadius="0,5,5,0" />
<!-- bla bla -->
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
I it possible that the user of this button can specify the CornerRadius? Can I use a TemplateBinding? But where should I bind to? (to Tag?)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
除了 Kent 的建议之外,您还可以创建一个附加属性来定义按钮上的 CornerRadius,并绑定到模板中的该属性
In addition to Kent's suggestions, you could also create an attached property to define the CornerRadius on the button, and bind to that property in the template
为了使用
TemplateBinding
,模板化控件上必须有一个属性(在本例中为Button
)。Button
没有CornerRadius
或等效属性,因此您的选择是: 对Tag
)来存储此信息。 这更快,但缺乏类型安全性,更难维护,并且会阻止该属性的其他用途。Button
并添加所需的属性,然后为该子类提供模板。 这需要更长的时间,但可以为您控制的消费者带来更好的体验。In order to use a
TemplateBinding
, there must be a property on the templated control (Button
, in this case).Button
does not have aCornerRadius
or equivalent property, so your options are:Tag
) to store this information. This is quicker, but lacks type safety, is harder to maintain, and prevents other uses of that property.Button
and add the propery you need, then provide a template for that subclass. This takes a little longer but yields a much nicer experience for consumers of your control.按钮类型没有 CornerRadius 属性,因此无法对其进行模板化。 我认为最简单的方法是创建一个继承自 Button 的新类,并为 CornerRadius 添加新的依赖属性。 像这样:
在 xaml 中,您可以像这样使用它:
绑定到 CornerRadius 的模板现在可以正常工作。
The button type doesn't have a property for CornerRadius, so templating this won't be possible. I think the easiest way is creating a new class which inherits from Button and add a new dependency property for the CornerRadius. Like this:
In xaml you can use it like:
A template binding to the CornerRadius will work without a problem now.