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

如何将ICommand的CanExecute绑定到FontIcon前景色实现状态切换?

问题场景

我有一个绑定了ToggleMode命令的Button控件,内部包含FontIcon和TextBlock。在Styles.xaml中已设置Button启用时前景色为白色,禁用时为浅灰色,TextBlock的前景色会随ToggleMode.CanExecute()的返回值正确切换,但FontIcon默认通过Foreground属性设为亮蓝色,需要在Button禁用时改为淡蓝色以体现禁用状态。

代码示例

布尔转换器

<local:BooleanConverter x:Key="CanExecuteToIconColorConverter">
    <local:BooleanConverter.True>
        <SolidColorBrush Color="{ThemeResource VividSkyBlueColor}" />
    </local:BooleanConverter.True>
    <local:BooleanConverter.False>
        <SolidColorBrush Color="{ThemeResource PaleVividSkyBlueColor}" />
    </local:BooleanConverter.False>
</local:BooleanConverter>

按钮初始代码

<Button Grid.Row="0" Width="150" Padding="10"
        Command="{x:Bind ToggleMode, Mode=OneWay}">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="3*"/>
        </Grid.ColumnDefinitions>
        <FontIcon FontSize="20" Grid.Column="0"
                  Glyph="{StaticResource mdi_toggle_off}"
                  FontFamily="{StaticResource MaterialDesignIconsOutlined}"
                  Foreground="{ThemeResource VividSkyBlueColor}"/>
        <TextBlock Grid.Column="1" Margin="10,0,0,0" Text="Toggle"/>
    </Grid>
</Button>

已尝试方案

  • 将FontIcon的Foreground直接绑定到命令,未生效
  • 订阅命令的CanExecuteChanged事件,未生效
  • 考虑订阅命令属性变更事件,但会产生大量样板代码,未采用

有效解决方案

参考@AndrewKeepCoding的回答,通过绑定Button的IsEnabled属性实现需求,修改后的代码如下:

<Button Grid.Row="0" Width="150" Padding="10"
        Command="{x:Bind ToggleMode, Mode=OneWay}"
        x:Name="ToggleModeButton">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="3*"/>
        </Grid.ColumnDefinitions>
        <FontIcon FontSize="20" Grid.Column="0"
                  Glyph="{StaticResource mdi_toggle_off}"
                  FontFamily="{StaticResource MaterialDesignIconsOutlined}"
                  Foreground="{x:Bind ToggleModeButton.IsEnabled, Mode=OneWay, Converter={StaticResource CanExecuteToIconColorConverter}}"/>
        <TextBlock Grid.Column="1" Margin="10,0,0,0" Text="Toggle"/>
    </Grid>
</Button>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 09:33:22