【发布时间】:2021-03-21 21:03:34
【问题描述】:
当我有一个具有以下样式的TextBox 时,Validation.HasError 属性会被触发并且可以正常工作。
<Style x:Key="ErrorStyle" TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)/ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
但是,当我将 ListView 与 ItemTemplate 一起使用时,它具有与上述相同样式的 TextBox,Validation.HasError 属性不会在 XAML 中触发并且没有任何变化。
XAML 代码摘要:
<!--User Control code-->
<ListView ItemsSource="{Binding DeploymentSettingEntries}"
ItemTemplate="{StaticResource DeploymentItemTemplate}">
</ListView>
<!--App.xaml code for Data Template and Error Style resource-->
<DataTemplate x:Key="DeploymentItemTemplate" DataType="{x:Type settings:SettingsEntry}">
<Grid IsSharedSizeScope="True">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<TextBox Grid.Column="0"
Style="{StaticResource ErrorStyle}"
Text="{Binding Value, UpdateSourceTrigger=PropertyChanged}"/>
</Grid>
</DataTemplate>
来自 ViewModel 的部件:
public class DeploymentConfigViewModel : ValidatableBindableBase, INotifyDataErrorInfo
{
private readonly IValidator<DeploymentConfigViewModel> validator;
private BindingList<SettingsEntry> deploymentSettingEntries;
public DeploymentConfigViewModel(IValidator<DeploymentConfigViewModel> validator)
{
this.validator = validator;
this.validator.ErrorsChanged += (s, e) => OnErrorsChanged(e);
}
public bool HasErrors => validator.HasErrors;
public sealed override void ValidateAllProperties()
{
validator.Validate(this);
}
public BindingList<SettingsEntry> DeploymentSettingEntries
{
get => deploymentSettingEntries;
set
{
deploymentSettingEntries = value;
deploymentSettingEntries.ListChanged +=
(sender, args) => ValidateAllProperties();
OnPropertyChanged();
}
}
我在我的 ViewModel 中调试了实现 INotifyDataErrorInfo 的 HasErrors 属性,并且在两种情况它都返回 True。
我尝试直接在我的 ListView 上调用 Validation.HasError 触发器或将 Style 放在我的用户控件中,但它们都不起作用..
有人知道为什么验证不会发生在 TextBox 而是整个 UserControl?
【问题讨论】:
-
为什么DataTemplate中的样式名称不一样?错误文本框样式
-
这只是一个复制和粘贴错误 - 我现在修复了它。不幸的是,这与真正的问题无关。
标签: c# wpf validation