我有一个类Person
,有两个属性FirstName
,LastName,
两个Constructors
,一个ICommand
和常用的东西和所需的INotifyPropertyChanged
东西IDataErrorInfo
:
class Person : ObservableCollection<Person>, INotifyPropertyChanged, IDataErrorInfo
{
string firstName, lastName;
#region Properties
[Required(ErrorMessage = "First Name is Required")]
[RegularExpression("test", ErrorMessage = "It's to be test")]
public string FirstName {
get => firstName;
set { firstName = value; OnPropertyChanged(); }
}
[Required]
[RegularExpression("test", ErrorMessage = "It also has to be test")]
public string LastName {
get => lastName;
set { lastName = value; OnPropertyChanged(); }
}
#endregion Properties
#region Constructors
public Person(){
AddToList = new Command(CanAdd, Add);
}
public Person(string fName, string lName){
FirstName = fName;
LastName = lName;
}
#endregion Constructors
#region Command
public ICommand AddToList { get; set; }
bool CanAdd(object para) => Validator.TryValidateObject(this, new ValidationContext(this), null, true);
void Add(object para){
Add(new Person(FirstName, LastName));
FirstName = LastName = null;
}
#endregion Command
#region INotifyPropertyChanged
public new event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string name = "") => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
#endregion INotifyPropertyChanged
#region IDataErrorInfo
public string Error => null;
public string this[string columnName] {
get {
var ValidationResults = new List<ValidationResult>();
if (Validator.TryValidateProperty(
GetType().GetProperty(columnName).GetValue(this),
new ValidationContext(this) { MemberName = columnName },
ValidationResults
)) return null;
return ValidationResults.First().ErrorMessage;
}
}
#endregion IDataErrorInfo
}
在xaml
我有两个TextBox
绑定到FirstName
Person LastName
,两个Label
用于验证错误消息,一个Button
绑定到 ICommand,添加Person
以下内容ListView
:
<Window ...>
<Window.Resources>
<local:Person x:Key="Person"/>
</Window.Resources>
<Grid DataContext="{StaticResource Person}">
<StackPanel>
<TextBox x:Name="Fname" Text="{Binding FirstName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
<Label Content="{Binding (Validation.Errors)[0].ErrorContent, ElementName=Fname}"/>
<TextBox x:Name="Lname" Text="{Binding LastName, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}"/>
<Label Content="{Binding (Validation.Errors).CurrentItem.ErrorContent, ElementName=Lname}"/>
<Button Content="Click" Command="{Binding AddToList}" />
<ListView x:Name="lv" ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="First Name" Width="200"
DisplayMemberBinding="{Binding FirstName}"/>
<GridViewColumn Header="Last Name" Width="200"
DisplayMemberBinding="{Binding LastName}" />
</GridView>
</ListView.View>
</ListView>
</StackPanel>
</Grid>
</Window>
它有效,如果名字和姓氏无效,我会收到错误消息,并且只要名字和姓氏中的任何一个无效,按钮就会保持禁用状态。我只想用 替换IDataErrorInfo
部分INotifyDataErrorInfo
。我必须在Person
课堂上进行哪些更改并xaml
保持相同的功能?