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

Avalonia UI:如何让TextBox在聚焦、失焦、禁用等状态下样式一致?

让Avalonia的TextBox在所有状态下保持一致外观

是否有办法让TextBox无论处于聚焦、失焦、禁用等状态,外观都保持一致?

我尝试通过定义样式实现,但TextBox聚焦后背景色还是会变化,当前的样式代码如下:

<Application.Styles>
    <FluentTheme /> 
    <Style Selector="TextBox">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>            
    </Style>
    <Style Selector="TextBox:focus">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>
    </Style>
    <Style Selector="TextBox:pointerover">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>
    </Style>
    <Style Selector="TextBox:focus-visible">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>
    </Style>
</Application.Styles>

要解决这个问题,你需要覆盖所有可能的控件状态选择器,包括禁用状态,确保样式优先级足够覆盖内置Fluent主题的样式。修改后的样式如下:

<Application.Styles>
    <FluentTheme /> 
    <!-- 默认状态 -->
    <Style Selector="TextBox">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>
        <Setter Property="Foreground" Value="#ffffff"/> <!-- 可选:保持禁用时文字颜色一致 -->
    </Style>
    <!-- 鼠标悬停状态 -->
    <Style Selector="TextBox:pointerover">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>
    </Style>
    <!-- 聚焦状态 -->
    <Style Selector="TextBox:focus">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>
    </Style>
    <!-- 可见聚焦状态 -->
    <Style Selector="TextBox:focus-visible">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>
    </Style>
    <!-- 禁用状态 -->
    <Style Selector="TextBox:disabled">
        <Setter Property="Background" Value="#323a46"/>
        <Setter Property="BorderBrush" Value="#323a46"/>
        <Setter Property="Foreground" Value="#ffffff"/> <!-- 可选:保持禁用时文字颜色一致 -->
    </Style>
</Application.Styles>

关键说明:

  • 必须显式覆盖TextBox:disabled状态,内置主题会默认修改禁用控件的背景和文字颜色
  • 确保所有状态都设置相同的Background和BorderBrush,完全覆盖主题的默认样式
  • 如果仍有部分状态未生效,可以检查是否遗漏了其他状态选择器(如:focus-within),或通过更具体的选择器(如给TextBox添加类名TextBox.my-static-textbox)提升样式优先级

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:25:06