将参数传递给模板

假设我已经定义了一个带圆角的按钮。

           

我可能这个按钮的用户可以指定CornerRadius吗? 我可以使用TemplateBinding吗? 但是我应该在哪里绑定? (标记?)

为了使用TemplateBinding ,模板化控件上必须有一个属性(在本例中为Button )。 Button没有CornerRadius或等效属性,因此您的选项是:

  • 硬编码模板中的值
  • 劫持另一个属性(如Tag )来存储此信息。 这样更快,但缺乏类型安全性,更难维护,并阻止该属性的其他用途。
  • 子类Button并添加您需要的属性,然后为该子类提供模板。 这需要更长的时间,但为您的控制消费者带来更好的体验。

除了Kent的建议之外,您还可以创建一个附加属性来定义按钮上的CornerRadius,并绑定到模板中的该属性

按钮类型没有CornerRadius的属性,因此无法进行模板化。 我认为最简单的方法是创建一个inheritance自Button的新类,并为CornerRadius添加一个新的依赖项属性。 像这样:

 using System.Windows; using System.Windows.Controls; namespace WpfApplication3 { public class RoundedButton:Button { public CornerRadius CornerRadius { get { return (CornerRadius) GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof (CornerRadius), typeof (RoundedButton), new UIPropertyMetadata()); } } 

在xaml中你可以使用它:

  

绑定到CornerRadius的模板现在可以正常工作。