如何更改 UWP 复选框的背景?

How to change checkbox's background for UWP?

我无法使用以下代码更改复选框的背景,但它适用于 Windows Store 应用程序 (Windows 8.1)。我想知道如何让它适用于 UWP?

this.checkBox.Background = new SolidColorBrush(Windows.UI.Colors.Yellow);
this.checkBox.Foreground = new SolidColorBrush(Windows.UI.Colors.Blue);

要更改复选框的 ForegroundBackground 颜色,您需要更新其模板。您可以通过 - 在可视化设计器中右键单击您的复选框,然后单击 编辑模板 > 编辑副本。这将为 CheckBox 创建默认模板。 (你可以查看整个模板here

此模板包含复选框的所有视觉状态。您将需要覆盖您需要的视觉状态。例如,您对 "UncheckedNormal" 状态执行类似的操作。

<VisualState x:Name="UncheckedNormal">
              <Storyboard>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="NormalRectangle"
                                           Storyboard.TargetProperty="Fill">
                  <DiscreteObjectKeyFrame KeyTime="0" Value="Your Fill Color here for only check part" />
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="NormalRectangle"
                                           Storyboard.TargetProperty="Stroke">
                  <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource SystemControlHighlightBaseHighBrush}" />
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                           Storyboard.TargetProperty="Foreground">
                  <DiscreteObjectKeyFrame KeyTime="0" Value="Your foreground color here" />
                </ObjectAnimationUsingKeyFrames>
                <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter"
                                           Storyboard.TargetProperty="Background">
                  <DiscreteObjectKeyFrame KeyTime="0" Value="Your background color here" />
                </ObjectAnimationUsingKeyFrames>
              </Storyboard>
</VisualState>

这也可以用 C# 编写,但它太复杂了,在 XAML 中编辑样式是推荐的样式设置方式。

希望这对您有所帮助。如果您有任何问题,请随时添加。