【发布时间】:2023-03-24 01:58:01
【问题描述】:
我正在使用 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>
如何在此验证的界面上显示错误消息?
【问题讨论】:
-
那控件肯定亮橘红色边框了?将 adornedelementplaceholder 和错误文本块放在停靠面板而不是网格中会发生什么?
-
什么都没有出现,该栏既不是橙色也不是消息。
标签: c# wpf ivalidatableobject