如何在UWP XAML出现错误时动态改变边框颜色?

7ivaypg9  于 2022-12-07  发布在  其他
关注(0)|答案(1)|浏览(128)

我已经绑定了error方法属性和text-block,这样当错误发生时,它会显示在表单中的文本框下面。但是我也想在错误发生时改变文本框的背景颜色。但是我不知道如何在错误发生时动态绑定border-brush属性和文本框。我已经分享了我的代码的一小部分。
XAML代码

<TextBlock
            Margin="0 110 0 12"
            Style="{StaticResource Label}"
            Text="Name"
            />

            <TextBox
               Margin="0 0 300 0" MaxLength="20" Text="{x:Bind ViewModel.Name, Mode=TwoWay}" 
             />
            <TextBlock Style="{StaticResource ErrorStyle}" Text="{x:Bind ViewModel.IsNameValid, Mode=TwoWay}"/>

检视模型

private string IsNameValid_;
    public string IsNameValid
    {
        get => this.IsNameValid_;
        set => SetProperty(ref this.IsNameValid_, value);
    }
  public async Task RegisterPatientInfo()
    {
        
        ValidationCheck(this.Name,);
      
    }

验证方法

public void ValidationCheck(string name, string kana, string patientNumber, string year, string month, string days)
    {

        //Name Validation
        var regexNamePattern = @"^([a-zA-Z]){0,20}$";
        Regex nameRegex = new Regex(regexNamePattern);
        if (!nameRegex.IsMatch(name))
        {
            this.IsNameValid = "";
        }
1aaf6o9v

1aaf6o9v1#

一种常见的方法是使用数据绑定和ValueConverter来动态更改UI元素的颜色。
这里有一个简单的演示,您可以参考。

色彩转换程式:

public class ColorConverter : IValueConverter 
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        SolidColorBrush brush = null;
        string IsNameValid = value as string;
        if (IsNameValid.Equals("123")) 
        {
            brush = new SolidColorBrush(Colors.Red);
        }
        return brush;
    }

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

XAML:

<Page.Resources>
    <local:ColorConverter x:Key="ColorConverter"/>
</Page.Resources>

  <TextBox Background="{x:Bind ViewModel.IsNameValid,Converter={StaticResource ColorConverter}, Mode=TwoWay}"/>

相关问题