在按钮模板上设置CornerRadius

我想要一个定义没有CornerRadius的Button和另外两个定义的Button,我该如何实现呢?

                    

正如Nitesh所说你在Button上没有CornerRadius属性,它是你在第一个样式中显示的Border的属性,只是复制你的第一个Style并更改CornerRadius,然后将它分配给相应的Style按钮。

             

在此处输入图像描述

您不仅限于您正在模板化的控件的依赖项属性。 在这种情况下,虽然Button没有CornerRadius属性,但Border确实如此,因此您可以使用Border.CornerRadius

    

使用此方法,您不再需要维护控件模板的多个副本。

只需像这样创建一个新的Button:

   

我将创建自己的自定义按钮类(inheritance自Button),其中包含CornerRadius依赖项属性。 然后,您的样式的目标类型将成为此新类,您可以使用模板绑定来设置角半径。

使用此方法,您不仅不需要维护控件模板的多个副本,而且每次要修改角半径时都不需要创建新样式。 您可以直接设置或绑定到您的CornerRadius依赖项属性。

所以你的控件代码看起来像这样:

 public class MyCustomButton : Button { public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.Register("CornerRadius", typeof(CornerRadius), typeof(MyCustomButton), new FrameworkPropertyMetadata(new CornerRadius(0))); public CornerRadius CornerRadius { get { return (CornerRadius)GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } } 

和XAML:

  

因此,对于不需要角半径的按钮,由于依赖属性将其默认为0,因此您无需执行任何操作。 对于具有角半径的那些,您只需将依赖项属性设置为适当的值,就像设置普通Border的CornerRadius属性一样。

您可以使用附加属性来设置按钮边框半径(对于文本框也是如此)。

为附加属性创建类

 public class CornerRadiusSetter { public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty); public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value); public static readonly DependencyProperty CornerRadiusProperty = DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius), typeof(CornerRadiusSetter), new UIPropertyMetadata(new CornerRadius(), CornerRadiusChangedCallback)); public static void CornerRadiusChangedCallback(object sender, DependencyPropertyChangedEventArgs e) { Control control = sender as Control; if (control == null) return; control.Loaded += Control_Loaded; } private static void Control_Loaded(object sender, EventArgs e) { Control control = sender as Control; if (control == null || control.Template == null) return; control.ApplyTemplate(); Border border = control.Template.FindName("border", control) as Border; if (border == null) return; border.CornerRadius = GetCornerRadius(control); } } 

然后,您可以使用附加属性语法设置多个按钮的样式,而不会出现样式重复: