You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过样式复用重写WinUI ToggleSwitch的内部边距

实现WinUI中ToggleSwitch无外围边距的复用方案

你可以通过以下两种常用方式实现配置复用,不用每次重复编写资源代码:

方法一:创建自定义Style

在页面或应用级别的Resources中定义包含边距资源的Style,之后给需要无外边距的ToggleSwitch指定该Style即可:

<!-- 在Page.Resources或App.xaml的Resources中添加 -->
<Style x:Key="NoMarginToggleSwitchStyle" TargetType="ToggleSwitch">
    <Style.Resources>
        <x:Double x:Key="ToggleSwitchPreContentMargin">0</x:Double>
        <x:Double x:Key="ToggleSwitchPostContentMargin">0</x:Double>
    </Style.Resources>
</Style>

<!-- 使用时直接引用Style -->
<ToggleSwitch Style="{StaticResource NoMarginToggleSwitchStyle}"
              Header="无外边距开关"/>

这种方式适合需要给ToggleSwitch附加其他样式属性(比如字体、颜色)的场景,能把所有配置集中在Style里统一管理。

方法二:共享资源字典

如果多个页面都需要用到这个无外边距配置,建议把边距资源单独放到资源字典文件中:

  1. 新建资源字典文件(比如ToggleSwitchResources.xaml),内容如下:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <x:Double x:Key="ToggleSwitchPreContentMargin">0</x:Double>
    <x:Double x:Key="ToggleSwitchPostContentMargin">0</x:Double>
</ResourceDictionary>
  1. 在需要使用的ToggleSwitch控件的Resources中合并该字典:
<ToggleSwitch>
    <ToggleSwitch.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="ToggleSwitchResources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </ToggleSwitch.Resources>
</ToggleSwitch>

也可以在页面级Resources中合并字典,这样该页面下所有ToggleSwitch都会自动应用这个边距配置;如果想全局生效,就合并到App.xaml的Resources里。

内容的提问来源于stack exchange,提问作者Haukman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 11:20:39