UWP中如何通过模板样式为Button设置各边不同的边框颜色
原生UWP的Border控件不支持单独为不同边设置不同边框色,可通过在Button控件模板中添加四个对应四边的独立Rectangle元素实现需求,无需新增自定义依赖属性,完整样式代码如下:
<Style TargetType="Button" BasedOn="{StaticResource DefaultButtonStyle}" > <Setter Property="Background" Value="White" /> <Setter Property="Foreground" Value="#3272B2" /> <Setter Property="BorderThickness" Value="1,1,1,2" /> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="Button"> <Grid Background="{TemplateBinding Background}"> <!-- 左侧边框 --> <Rectangle Fill="Red" HorizontalAlignment="Left" Width="{Binding BorderThickness.Left, RelativeSource={RelativeSource TemplatedParent}}" /> <!-- 顶部边框 --> <Rectangle Fill="Green" VerticalAlignment="Top" Height="{Binding BorderThickness.Top, RelativeSource={RelativeSource TemplatedParent}}" /> <!-- 右侧边框 --> <Rectangle Fill="Yellow" HorizontalAlignment="Right" Width="{Binding BorderThickness.Right, RelativeSource={RelativeSource TemplatedParent}}" /> <!-- 底部边框 沿用原有蓝色 --> <Rectangle Fill="#155EA8" VerticalAlignment="Bottom" Height="{Binding BorderThickness.Bottom, RelativeSource={RelativeSource TemplatedParent}}" /> <!-- 内容承载区 --> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" Margin="{TemplateBinding Padding}" Content="{TemplateBinding Content}" ContentTemplate="{TemplateBinding ContentTemplate}" /> <!-- 原有按钮交互状态特效可自行在这里补充,比如PointerOver、Pressed的视觉状态 --> <VisualStateManager.VisualStateGroups> <VisualStateGroup x:Name="CommonStates"> <VisualState x:Name="Normal" /> <VisualState x:Name="PointerOver"> <!-- 按需添加悬停效果 --> </VisualState> <VisualState x:Name="Pressed"> <!-- 按需添加按压效果 --> </VisualState> <VisualState x:Name="Disabled"> <!-- 按需添加禁用效果 --> </VisualState> </VisualStateGroup> </VisualStateManager.VisualStateGroups> </Grid> </ControlTemplate> </Setter.Value> </Setter> </Style>
- 四个边的颜色直接修改对应
Rectangle的Fill属性值即可,无需新增额外样式属性 - 边框粗细复用原
BorderThickness属性的对应边数值,原有配置逻辑无需调整 - 可自行在
VisualStateManager节点补充交互状态的视觉效果,和原生按钮交互逻辑保持一致
内容的提问来源于stack exchange,提问作者Sujith
相关产品推荐
相关产品推荐

