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

C# UWP TextBox.Resources中SolidColorBrush绑定失效问题咨询

绑定失效原因

  • 数据上下文继承失效:放在TextBox.Resources里的SolidColorBrush不属于可视化树元素,默认无法继承到外层TextBox的DataContext,因此绑定表达式找不到对应的FontColour属性源。
  • 类型不匹配:你定义的FontColour是SolidColorBrush类型,但你当前绑定的目标是SolidColorBrush.Color(Color值类型),二者类型不匹配,即使能找到数据源也无法完成赋值。

解决方案

方案1:修正绑定路径与数据源指向

修改资源中SolidColorBrush的绑定表达式,通过RelativeSource定位到父级TextBox获取DataContext,同时明确取FontColour的Color属性即可:

<TextBox Text="{Binding EventLog}"
         Foreground="{Binding FontColour}"
         Background="{Binding ColourTheme5}">
    <TextBox.Resources>
        <SolidColorBrush x:Key="TextControlForegroundPointerOver"
                         Color="{Binding DataContext.FontColour.Color, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}"
                         Opacity="1" />
    </TextBox.Resources>
</TextBox>

如果是WinUI/UWP环境,RelativeSource写法调整为:

Color="{Binding FontColour.Color, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=TextBox}}"

方案2:重写TextBox控件模板(更适合全局主题切换)

直接修改TextBox的默认样式,将指针悬停状态的前景色直接绑定到控件本身的Foreground属性,不需要单独维护资源键,适配性更强:

<TextBox Text="{Binding EventLog}"
         Foreground="{Binding FontColour}"
         Background="{Binding ColourTheme5}">
    <TextBox.Style>
        <Style TargetType="TextBox" BasedOn="{StaticResource DefaultTextBoxStyle}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TextBox">
                        <!-- 其余模板代码保持默认即可,仅修改PointerOver状态的前景色设置 -->
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualState x:Name="PointerOver">
                                <Storyboard>
                                    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentElement" Storyboard.TargetProperty="Foreground">
                                        <DiscreteObjectKeyFrame KeyTime="0" Value="{TemplateBinding Foreground}" />
                                    </ObjectAnimationUsingKeyFrames>
                                </Storyboard>
                            </VisualState>
                        </VisualStateGroup>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TextBox.Style>
</TextBox>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 05:51:03