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

WinUI 3.0 Desktop 只读TextBox鼠标悬停时背景色被重置问题求解

解决方案

你遇到的问题本质是WinUI 3控件的默认样式内置了交互状态逻辑,悬停、聚焦等状态会动态覆盖直接设置的Background属性值,只读状态下也有独立的交互状态样式规则,直接修改属性无法覆盖状态切换的逻辑。以下是两种可行的落地方式:

方案1:重写控件资源(最简易,无需修改控件模板)

WinUI的TextBox默认样式使用标准资源键定义不同状态下的背景笔刷,你只需要在TextBox的资源字典中重写只读状态相关的资源键,即可统一所有交互场景下的背景色:

<TextBox IsReadOnly="True" Text="The content...">
    <TextBox.Resources>
        <!-- 只读默认状态背景 -->
        <SolidColorBrush x:Key="TextControlBackgroundReadOnly" Color="SlateGray"/>
        <!-- 只读状态鼠标悬停背景 -->
        <SolidColorBrush x:Key="TextControlBackgroundPointerOverReadOnly" Color="SlateGray"/>
        <!-- 只读状态控件聚焦背景 -->
        <SolidColorBrush x:Key="TextControlBackgroundFocusedReadOnly" Color="SlateGray"/>
        <!-- 只读状态鼠标按下背景 -->
        <SolidColorBrush x:Key="TextControlBackgroundPressedReadOnly" Color="SlateGray"/>
    </TextBox.Resources>
</TextBox>

该方案不需要修改控件模板,仅需局部重写资源,适配单个控件或全局样式复用都很方便。

方案2:后台事件强制覆盖(适合临时快速处理)

如果不想写XAML样式,也可以通过监听控件的交互事件,每次状态变化时强制重写背景色:

  1. 先给TextBox绑定对应事件:
<TextBox 
    IsReadOnly="True" 
    Background="SlateGray" 
    Text="The content..."
    PointerEntered="TextBox_StateChanged"
    PointerExited="TextBox_StateChanged"
    GotFocus="TextBox_StateChanged"
    LostFocus="TextBox_StateChanged"
/>
  1. 后台实现事件逻辑:
using Microsoft.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;

private void TextBox_StateChanged(object sender, RoutedEventArgs e)
{
    var textBox = sender as TextBox;
    if (textBox != null && textBox.IsReadOnly)
    {
        textBox.Background = new SolidColorBrush(Colors.SlateGray);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 23:06:01