一段时间以来,我一直在尝试创建一个具有圆角的按钮,其圆角实际上是半圆
我实现这一点的想法是将Border
的CornerRadius
绑定到按钮高度的一半(我知道除了转换器之外,我无法在XAML中进行计算)。唉,这似乎是不可能的,因为TemplateBinding
没有提出任何建议。
<ControlTemplate TargetType="Button">
<Grid>
<Border CornerRadius={???}>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
Margin="{TemplateBinding Padding}"
FontSize="{TemplateBinding FontSize}"
FontFamily="{TemplateBinding FontFamily}" />
</Border>
</Grid>
</ControlTemplate>
也许我可能需要创建一个从具有CornerRadius
依赖属性的按钮派生的新控件。但在我继续之前,是否有任何方法可以在XAML中实现它
顺便说一句,如果重要的话,我是为UWP应用程序做这件事的?
但在我继续之前,有没有办法在XAML中实现它?
是的,我认为这是可能的。但需要转换器
我知道除了转换器之外,我无法在XAML中进行计算
是的,我们需要在转换器中进行计算,CornerRadius是CornerRadius
类型,我们不能直接将双重类型的Height/2
绑定到它。这里我使用了Button
的高度来计算半径。
我实现这一点的想法是将Border的CornerRadius绑定到按钮高度的一半。
我认为没有必要使用Border
,因为Button
、Grid
和ContentPresenter
的ControlTemplate
也具有CornerRadius
属性。
例如:
<ControlTemplate TargetType="Button">
<Grid x:Name="RootGrid" Background="{TemplateBinding Background}"
CornerRadius="{Binding Height, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource cvt}}">
<ContentPresenter x:Name="ContentPresenter" AutomationProperties.AccessibilityView="Raw"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
ContentTemplate="{TemplateBinding ContentTemplate}"
ContentTransitions="{TemplateBinding ContentTransitions}"
Content="{TemplateBinding Content}"
HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
Padding="{TemplateBinding Padding}"
VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
CornerRadius="{Binding Height, RelativeSource={RelativeSource Mode=TemplatedParent}, Converter={StaticResource cvt}}" />
</Grid>
</ControlTemplate>
<local:HeightToCornerRadiusConverter x:Key="cvt" />
我的HeightToCornerRadiusConverter
是这样的:
public class HeightToCornerRadiusConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
var height = (double)value;
CornerRadius radius = new CornerRadius(height / 2);
return radius;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
这里有一个问题,正如您所看到的,CornerRadius
绑定到Button
的Height
,所以在使用此样式时,我们需要将高度设置为Button
,这一点很重要。