我是MVVM的新手,剛剛在MVVM模式之後啓動了我的第一個項目。我有一個問題試圖使用IDataErrorInfo接口來驗證ObservableCollection。我的ObservableCollection看起來是這樣的:使用MVVM驗證ViewModel中綁定的ObservableCollection模式
ObservableCollection<Magazine> magazineRepository;
public ObservableCollection<Magazine> MagazineRepository
{
get { return magazineRepository; }
set
{
if (value != null)
{
bladRepository = value;
OnPropertyChanged("MagazineRepository");
}
}
}
我的XAML這樣的:
<ListBox x:Name="listMagazineRepository"
Grid.ColumnSpan="2"
ItemsSource="{Binding}"
DataContext="{Binding MagazineRepository}"
DisplayMemberPath="Navn"
SelectedItem="{Binding Path=SelectedItem}"/>
<TextBox x:Name="txtName" Grid.Row="1" Grid.Column="0"
Text="{Binding ElementName=listMagazineRepository, Path=SelectedItem.Navn, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
<TextBox x:Name="txtPrice" Grid.Row="2" Grid.Column="0"
Text="{Binding ElementName=listMagazineRepository, Path=SelectedItem.Pris, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" />
,當你選擇一個項目,所選對象的屬性顯示在文本框,它只是包含對象的簡單列表框然後綁定到列表框對象。
我的問題是,當我像這樣設置我的代碼時,唯一可以弄清楚如何驗證數據的方法是在域模型中,這實際上不是一種好的做法,我想在它到達那裏之前在ViewModel中驗證。基本上我想驗證MagazineRepository中的每個屬性,在ViewModel中,你將如何去做這件事?如果我的問題缺乏信息,請讓我知道,我將提供所需的詳細信息。如果我的問題缺乏信息,請告訴我,我將提供所需的詳細信息。
非常感謝。
嗯,我沒有在您的代碼中看到您發佈的ViewModel,但典型的方式將是您的ViewModel實現IDataErrorInfo – Alan
對不起,我認爲這是暗示。該集合在我的ViewModel中,確實實現了IDataErrorInfo,但是當文本框更改集合中的一個屬性時,我需要驗證該屬性,並且我無法弄清楚該怎麼做。所以有兩個文本框每個綁定到集合中的一個屬性,當屬性發生變化時,我需要對它進行驗證,按照我使用IDataErrorInfo學習的方式進行驗證,我只能驗證整個集合。 –