我有一个字符串项目的 ListBox,我想在每次添加或删除字符串时验证字符串。
下面是我拼凑在一起的代码,但问题是当 ObservableCollection 地址发生变化时,ValidateAddresses 永远不会被调用。
预期行为是,当发现无效字符串时,应在 ListBox 周围显示红色边框,并带有显示错误消息的工具提示。
这个 INotifyDataErrorInfo 设置适用于 TextBoxes,所以我不知道我在这里做错了什么。
视图模型
[CustomValidation(typeof(ItemViewModel), "ValidateAddresses")]
public ObservableCollection<string> Addresses
{
get
{
return item.Addresses;
}
set
{
item.Addresses = value;
NotifyPropertyChanged(nameof(Addresses));
}
}
XAML
<Grid>
<Grid.Resources>
<Style TargetType="ListBox">
<Setter Property="Margin" Value="5"/>
<Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
<Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate x:Name="TextErrorTemplate">
<DockPanel LastChildFill="True">
<AdornedElementPlaceholder>
<Border BorderBrush="Red" BorderThickness="2"/>
</AdornedElementPlaceholder>
<TextBlock Foreground="Red"/>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<ListBox ItemsSource="{Binding Path=Item.Addresses, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}" SelectedIndex="{Binding Path=SelectedAddress, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
验证方法(从未调用)
public static ValidationResult ValidateAddresses(object obj, ValidationContext context)
{
ItemViewModel item = (ItemViewModel)context.ObjectInstance;
if (item.Addresses.Count > 0)
{
foreach (string address in item.Addresses)
{
if (Regex.IsMatch(address, @"[^\w]"))
return new ValidationResult($"{address} is not a valid address.", new List<string> { "Addresses" });
}
}
return ValidationResult.Success;
}