首页 > 解决方案 > 如何在 WPF 中使用 IValidatableObject 显示错误消息?

问题描述

我正在使用 IValidatableObject 在 wpf 中验证我的模板。但是,错误信息不会返回到界面。然而,值得澄清的是验证是有效的。唯一的问题是消息没有显示在界面中。

public string Host
{
   get => _host;
   set
   {
       _host = value;
       OnPropertyChanged();
    }
}

public string Port
{
   get => _port;
   set
   {
     _port = value;
     OnPropertyChanged();
   }
}

public string User
{
    get => _user;
    set
    {
      _user = value;
      OnPropertyChanged();
     }
}


public bool IsEmptyOrNull(string value) => string.IsNullOrWhiteSpace(value);

public IEnumerable<ValidationResult> Validate()
{
   var results = new List<ValidationResult>();
   var context = new ValidationContext(this);
   Validator.TryValidateObject(this, context, results, true);
   return results;
}

public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
  if (IsEmptyOrNull(Host))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Host) });
  }
  if (IsEmptyOrNull(Port))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Port) });
  }
  if (IsEmptyOrNull(User))
  {
     yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(User) });
  }
  if (IsEmptyOrNull(Password))
  {
     yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(Password) });
  }
  if (IsEmptyOrNull(DataBase))
  {
      yield return new ValidationResult(Resources.EmptyOrNull, new[] { nameof(DataBase) });
  }
}

这里接口XML

 <TextBox x:Name="HostTextBox" Text="{Binding AppSetting.Host,UpdateSourceTrigger=LostFocus, NotifyOnValidationError=True, ValidatesOnDataErrors=True, ValidatesOnExceptions=True, ValidatesOnNotifyDataErrors=True}"  Validation.ErrorTemplate="{StaticResource ErrorTemplate}" HorizontalAlignment="Left" Width="200" Margin="5,0,0,0" BorderBrush="#FF5774CB" mah:TextBoxHelper.Watermark="Localhost" TabIndex="1" FontSize="14"/>
<ControlTemplate x:Key="ErrorTemplate">
     <Border BorderBrush="OrangeRed" BorderThickness="2">
         <Grid>
            <AdornedElementPlaceholder/>
            <TextBlock Text="{Binding [0].ErrorContent}" Foreground="OrangeRed" VerticalAlignment="Center" HorizontalAlignment="Right"
Margin="0,0,4,0"/>
        </Grid>
    </Border>
</ControlTemplate>

如何在此验证的界面上显示错误消息?

标签: c#wpfivalidatableobject

解决方案


您的问题是因为 IValidateObject 只返回那些验证结果。

WPF 不关心它们。

您需要实现 inotifydataerrorinfo 或 WPF 理解的其他接口并在其中使用这些结果。

您可以调整我在此使用的代码:

https://gallery.technet.microsoft.com/scriptcenter/WPF-Entity-Framework-MVVM-78cdc204

看一下 BaseEntity 中的代码。


推荐阅读