此 XAML 元素绑定到我的视图模型中的 ListCollectionView:
<Style x:Key="ErrorStyle" TargetType="{x:Type Control}">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
<Setter Property="Background" Value="Salmon"/>
</Trigger>
</Style.Triggers>
</Style>
...
<controls:AutoCompleteBox Grid.Column="1" Grid.Row="0" Margin="5" Height="20" Width="270" HorizontalAlignment="Left" VerticalAlignment="Center"
Name="typeName"
Style="{StaticResource ErrorStyle}"
Text="{Binding Path=AirframeCollectionView/TypeName, UpdateSourceTrigger=LostFocus, Mode=TwoWay,
ValidatesOnNotifyDataErrors=True,
NotifyOnValidationError=True,
ValidatesOnExceptions=True}"
ItemsSource="{Binding Path=TypeNames}"
IsTextCompletionEnabled="True"
FilterMode="Contains"
MinimumPrefixLength="3">
</controls:AutoCompleteBox>
ListCollectionView 是这样定义的:
public ListCollectionView AirframeCollectionView
{
get
{
return this.airframeCollectionView;
}
set
{
this.airframeCollectionView = value;
this.RaisePropertyChanged("AirframeCollectionView");
}
}
并初始化:
this.currentAirframes = new ObservableCollection<Airframe>(this.UnitOfWork.Airframes.GetAirframesForRegistration(this.SearchRegistration));
this.AirframeCollectionView = (ListCollectionView)CollectionViewSource.GetDefaultView(this.currentAirframes);
在验证 AirframeCollectionView/TypeName 时,我使用的是 INotifyDataErrorInfo 接口,因此:
private readonly Dictionary<string, ICollection<string>> validationErrors = new Dictionary<string, ICollection<string>>();
public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged;
public bool HasErrors
{
get { return this.validationErrors.Count > 0; }
}
public IEnumerable GetErrors(string propertyName)
{
if (string.IsNullOrEmpty(propertyName) || !this.validationErrors.ContainsKey(propertyName))
{
return null;
}
return this.validationErrors[propertyName];
}
private void RaiseErrorsChanged(string propertyName)
{
if (this.ErrorsChanged != null)
{
this.ErrorsChanged(this, new DataErrorsChangedEventArgs(propertyName));
}
}
为了引发错误,我一直在这样做:
this.validationErrors["AirframeCollectionView/TypeName"] = validationErrors;
this.RaiseErrorsChanged("AirframeCollectionView/TypeName");
但是,这不会触发 UI 中的错误响应。我将属性名称从“AirframeCollectionView/TypeName”更改为“TypeName”,但这也不起作用。在调试器中,我确认validationErrors 加载了错误,并且ErrorsChanged 是使用提供的属性名称触发的。
请注意,当我在模型而不是 ViewModel 中实现 INotifyDataErrorInfo 时,这一切正常,但出于各种原因,我希望实现在 ViewModel 中。
问题
设置 DataErrorsChangedEventArgs 并触发 ErrorsChanged 时,我必须使用什么属性名称格式?或者我这里还有其他结构性问题吗?