这是我的代码:
<StackPanel Name="stackPanelMain" Orientation="Vertical">
<RadioButton Content="Work" Style="{StaticResource Rick_RadioButtonOption}"/>
<RadioButton Content="Non-Work" Style="{StaticResource Rick_RadioButtonOption}"/>
</StackPanel>
样式如下:
<Style TargetType="RadioButton" x:Key="Rick_RadioButtonOption">
<Setter Property="Background" Value="White" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Margin" Value="5" />
<Setter Property="FontSize" Value="18" />
<Setter Property="Padding" Value="27" />
</Style>
我增加了填充,所以它更明显发生了什么。文本按预期/要求居中,但实际的单选按钮保持在左上角:
如何让单选按钮垂直居中并稍微向右倾斜?我试过解决方案 here但它不适用于我的情况。
编辑 根据@asitis 的要求——这就是我在样式中设置这两个属性时得到的结果:
<Setter Property="Background" Value="Red" />
<Setter Property="Foreground" Value="Red" />
最佳答案
这可以通过修改 RadioButton
的默认样式来完成。 .您可以使用 LiveVisualTree
查看 RadioButton
的默认样式, 一个 RadioButton
实际上是一个 Grid
,其中包含另一个 Grid
与 3 Ellipses
和一个 ContentPresenter
像这样:
使用 Live Visual Tree可以实时查看你正在运行的XAML代码,你可以在VS2015中调试应用程序时使用这个工具,在vs2015的左侧打开它:
如果您编辑 RadioButton
的副本的默认样式,可以看到Grid
与 3 Ellipses
是这样的 <Grid Height="32" VerticalAlignment="Top">
.这就是为什么你的 Ellipses
在顶部。所以你可以像这样自定义样式:
<Style x:Key="RadioButtonStyle" TargetType="RadioButton">
<Setter Property="Background" Value="Transparent" />
<Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}" />
<!--<Setter Property="Padding" Value="8,6,0,0" />-->
<Setter Property="Padding" Value="27" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="HorizontalContentAlignment" Value="Left" />
<Setter Property="VerticalContentAlignment" Value="Top" />
<Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}" />
<Setter Property="FontSize" Value="18" />
<Setter Property="Margin" Value="5" />
<Setter Property="MinWidth" Value="120" />
<Setter Property="UseSystemFocusVisuals" Value="True" />
<Setter Property="Template">
......
<Grid Height="32" VerticalAlignment="Center">
<Ellipse x:Name="OuterEllipse" Height="20" Stroke="{ThemeResource SystemControlForegroundBaseMediumHighBrush}" StrokeThickness="{ThemeResource RadioButtonBorderThemeThickness}" UseLayoutRounding="False" Width="20" />
<Ellipse x:Name="CheckOuterEllipse" Fill="{ThemeResource SystemControlHighlightTransparentBrush}" Height="20" Opacity="0" Stroke="{ThemeResource SystemControlHighlightAltAccentBrush}" StrokeThickness="{ThemeResource RadioButtonBorderThemeThickness}" UseLayoutRounding="False" Width="20" />
<Ellipse x:Name="CheckGlyph" Fill="{ThemeResource SystemControlHighlightAltBaseMediumHighBrush}" Height="10" Opacity="0" UseLayoutRounding="False" Width="10" />
</Grid>
......
</Style>
顺便修改一下RadioButton
的模板,我们可以在“Document Outline”中选中“[RadioButton]”并右击,然后选择“Edit Template”→“编辑副本...”。
关于c# - XAML UWP 单选按钮图标居中对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34875232/