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

如何在UWP XAML中发生错误时动态修改TextBox边框颜色

解决TextBox错误状态下动态修改边框颜色的问题

步骤1:完善ViewModel的错误状态属性

首先在ViewModel中新增一个布尔属性,专门标记名称输入是否存在错误:

private bool _isNameInvalid;
public bool IsNameInvalid
{
    get => _isNameInvalid;
    set => SetProperty(ref _isNameInvalid, value);
}

private string _isNameValid;
public string IsNameValid
{
    get => _isNameValid;
    set => SetProperty(ref _isNameValid, value);
}

修正验证方法的逻辑,验证不通过时同时设置错误提示文本和错误状态;验证通过时重置状态:

public void ValidationCheck(string name)
{
    var regexNamePattern = @"^([a-zA-Z]){0,20}$";
    Regex nameRegex = new Regex(regexNamePattern);
    
    if (!nameRegex.IsMatch(name))
    {
        IsNameValid = "名称仅支持英文字母,长度不超过20位";
        IsNameInvalid = true;
    }
    else
    {
        IsNameValid = string.Empty;
        IsNameInvalid = false;
    }
}

步骤2:绑定TextBox的BorderBrush

提供两种常用实现方式:

方式一:使用DataTrigger(推荐)

给TextBox定义Style,通过DataTrigger监听错误状态,动态切换边框颜色:

<TextBox
    Margin="0 0 300 0" 
    MaxLength="20" 
    Text="{x:Bind ViewModel.Name, Mode=TwoWay}">
    <TextBox.Style>
        <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
            <!-- 默认边框颜色,可替换为项目中的默认样式 -->
            <Setter Property="BorderBrush" Value="#FFABADB3" />
            <Style.Triggers>
                <DataTrigger Binding="{x:Bind ViewModel.IsNameInvalid, Mode=OneWay}" Value="True">
                    <!-- 错误状态下的边框颜色 -->
                    <Setter Property="BorderBrush" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </TextBox.Style>
</TextBox>

方式二:使用值转换器

先创建布尔值到Brush的转换器类:

public class BoolToBrushConverter : IValueConverter
{
    public Brush TrueBrush { get; set; } = Brushes.Red;
    public Brush FalseBrush { get; set; } = Brushes.Gray;

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return value is bool isInvalid && isInvalid ? TrueBrush : FalseBrush;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

在XAML的资源节点中声明转换器:

<Page.Resources>
    <local:BoolToBrushConverter x:Key="BoolToBrushConverter" 
                                TrueBrush="Red" 
                                FalseBrush="#FFABADB3" />
</Page.Resources>

最后绑定TextBox的BorderBrush属性:

<TextBox
    Margin="0 0 300 0" 
    MaxLength="20" 
    Text="{x:Bind ViewModel.Name, Mode=TwoWay}"
    BorderBrush="{x:Bind ViewModel.IsNameInvalid, Mode=OneWay, Converter={StaticResource BoolToBrushConverter}}" />

注意事项

  • x:Bind使用OneWay模式即可,错误状态仅需从ViewModel同步到UI,无需反向绑定。
  • 验证逻辑必须覆盖验证通过的场景,确保错误状态和提示文本能被正确重置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 21:39:19