我有一个Model
被调用的PhoneModel
和一个ViewModel
被调用PersonViewModel
的,它们都是 impelementsINotifyPropertyChanged
和IDataErrorInfo
. 在PersonViewModel
中,我有一个ObservableCollection<PhoneModel> Phones
属性显示ItemsControl
在我的视图中。所以,我创建了一些Command
s 来添加和删除PhoneModel
项目Phones
。但是在添加、编辑和删除它们时,Validation
没有被解雇。如何强制ItemsControl
验证其内容?有什么办法吗?
public class PhoneModel : INotifyPropertyChanged, IDataErrorInfo {
// has some validation roles and IDataErrorInfo is implemented full
public string Number { get; set; }
}
public class PersonViewModel : INotifyPropertyChanged, IDataErrorInfo {
public ObservableCollection<PhoneModel> Phones { get; set /* implements INotifyPropertyChanged */ ; }
}
并认为:
<ItemsControl ItemsSource="{Binding Phones}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBox
Text="{Binding Number,
UpdateSourceTrigger=PropertyChanged,
Mode=TwoWay,
ValidatesOnExceptions=True,
NotifyOnValidationError=True,
ValidatesOnDataErrors=True}"
/>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
你能帮我吗?提前致谢。
更新 1
我尝试@Michael G
了答案,但仍然无效。我的代码在这里:
1)我添加了一个集合更改事件处理程序:
Phones.CollectionChanged += PhonesChanged;
2)在其中我尝试:
void PhonesChanged(object sender, NotifyCollectionChangedEventArgs e) {
if(e.Action != NotifyCollectionChangedAction.Remove)
return;
var model = e.OldItems[0] as PhoneModel;
if(model != null) {
model.Validate();
OnPropertyChanged(() => Phones);
}
}
3)我也尝试听每个电话项目的属性改变:
foreach(var phone in Phones)
phone.PropertyChanged += new PropertyChangedEventHandler(phone_PropertyChanged);
和:
void phone_PropertyChanged(object sender, PropertyChangedEventArgs e) {
var phone = sender as PhoneModel;
if(phone == null)
return;
phone.Validate();
OnPropertyChanged(() => Phones);
}