我的验证在第一个例子中起作用,但是当我从一个Tab项移动到另一个时,验证消失。如何使INotifyDataErrorInfo错误持续到更正为止?
我会期望这个状态是持久性的,直到用户在这种情况下输入有效的传递条件。
也许这是预期的行为,我错过了文档中的某些东西。
在我的应用程序有一个MainWindow.xaml和MainWindowViewModel.cs作为其的DataContext从一个BaseViewModel.cs实现INotifyPropertyChanged的,并INotifyDataErrorInfo继承。然后,我创建了一个自定义ValidationAttribute,称为FilePath.cs。
MainWindow.xaml由带有两个选项卡项的选项卡控件组成。只有一个文本框已经实现了我的验证。这是在验证不正确时通知我的意义上的。在这个例子中,文件路径不存在。
MainWindow.xaml
<TabControl>
<TabItem Header="Boxs">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Grid.Column="0"
Grid.Row="0"
Content="File Path" />
<TextBox Grid.Column="1"
Grid.Row="0"
Margin="5,5,5,5"
Text="{Binding FilePath,
Mode=TwoWay,
NotifyOnValidationError=True,
ValidatesOnNotifyDataErrors=True,
UpdateSourceTrigger=PropertyChanged}" />
</Grid>
</TabItem>
<TabItem Header="Blank"/>
</TabControl>
MainViewModel.cs
public class MainWindowViewModel : BaseViewModel
{
private string filePath;
[FilePath]
public string FilePath
{
get { return filePath; }
set
{
filePath = value;
ValidateProperty(value);
NotifyPropertyChanged(FilePath);
}
}
}
FilePath.cs
public sealed class FilePath : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (!Directory.Exists((string)value))
{
return new ValidationResult("Requires Valid File Path",
new string[] { validationContext.MemberName });
}
return ValidationResult.Success;
}
}
将具有校验,看起来很有希望。很高兴知道它为什么。 – metoyou