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

如何将WPF的Style Trigger转换为UWP实现?UWP无原生Trigger支持

WPF Trigger 转 UWP 实现方案

UWP 不支持 WPF 原生的 Trigger 特性,针对你的需求(当TextBlock的IsEnabled为False时修改前景色),可以用以下两种常用方案实现:

方案一:Style 结合 Setter.Condition(最接近 WPF Trigger 写法)

UWP 的 Style 支持通过 Setter.Condition 实现属性的条件赋值,逻辑和 WPF Trigger 完全匹配:

<TextBlock Text="Lorem ipsum dolor sit">
    <TextBlock.Style>
        <Style TargetType="TextBlock">
            <!-- 默认前景色 -->
            <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
            <!-- 禁用状态下的前景色 -->
            <Setter Property="Foreground" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}">
                <Setter.Condition>
                    <Condition Property="IsEnabled" Value="False"/>
                </Setter.Condition>
            </Setter>
        </Style>
    </TextBlock.Style>
</TextBlock>

说明:

  • UWP 中无需{x:Type}语法,直接指定TargetType="TextBlock"即可
  • 替换 WPF 的SystemColors.GrayTextBrushKey为 UWP 原生禁用态系统资源SystemControlDisabledBaseMediumLowBrush,用{ThemeResource}自动适配深色/浅色主题
  • 通过Setter.Condition绑定IsEnabled属性,条件满足时自动触发Setter

方案二:使用 VisualStateManager

如果需要更复杂的状态切换逻辑,可借助VisualStateManager实现:

<Grid>
    <TextBlock x:Name="MyTextBlock" Text="Lorem ipsum dolor sit"/>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
            <!-- 正常启用状态 -->
            <VisualState x:Name="Enabled"/>
            <!-- 禁用状态 -->
            <VisualState x:Name="Disabled">
                <VisualState.StateTriggers>
                    <StateTrigger IsActive="{Binding ElementName=MyTextBlock, Path=IsEnabled, Converter={StaticResource BooleanNegationConverter}}"/>
                </VisualState.StateTriggers>
                <VisualState.Setters>
                    <Setter Target="MyTextBlock.Foreground" Value="{ThemeResource SystemControlDisabledBaseMediumLowBrush}"/>
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</Grid>

配套自定义转换器代码

UWP 没有内置布尔值反转转换器,需要自行实现:

public class BooleanNegationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return !(bool)value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return !(bool)value;
    }
}

并在页面资源中声明:

<Page.Resources>
    <local:BooleanNegationConverter x:Key="BooleanNegationConverter"/>
</Page.Resources>

说明:

  • 若使用Button这类自带默认模板的控件,其模板内已包含CommonStates,可直接在模板中修改对应VisualState,无需额外容器

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:03:21