我遇到了 IDataErrorInfo 问题,这是一个示例
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new MainWindowViewModel();
}
}
public class MainWindowViewModel : INotifyPropertyChanged, IDataErrorInfo
{
public List<Person> _source1 = null;
public List<Person> Source1
{
get
{
return _source1 ?? (_source1 = new List<Person>()
{
new Person(){ Nom ="one"}
});
}
}
public List<Person> _source2 = null;
public List<Person> Source2
{
get
{
return _source2 ?? (_source2 = new List<Person>()
{
new Person(){ Nom ="two"}
});
}
}
private Person _selectedItem1;
public Person SelectedItem1 { get { return _selectedItem1; } set { _selectedItem1 = value; RaisePropertyChanged("SelectedItem1"); } }
private Person _selectedItem2;
public Person SelectedItem2 { get { return _selectedItem2; } set { _selectedItem2 = value; RaisePropertyChanged("SelectedItem2"); } }
public MainWindowViewModel()
{
//This is the actual way, i solve my problem
//this.PropertyChanged += (sender, e) =>
// {
// if (e.PropertyName == "SelectedItem1")
// {
// RaisePropertyChanged("SelectedItem2");
// }
// };
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public string Error
{
get { throw new NotImplementedException(); }
}
public string this[string columnName]
{
get {
string errors= string.Empty;
if (columnName == "SelectedItem2")
{
if(this.SelectedItem1 != null && this.SelectedItem2 == null)
errors = "erreur";
}
return errors;
}
}
}
public class Person
{
public string Nom { get; set; }
}
如您所见,我必须告知 SelectedItem2 很奇怪,因为 SelectedItem1 被选中,但红角没有出现。这是xaml代码。
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<ComboBox ItemsSource="{Binding Path=Source1}" DisplayMemberPath="Nom" SelectedItem="{Binding Path=SelectedItem1}"/>
<ComboBox ItemsSource="{Binding Path=Source2}" DisplayMemberPath="Nom" SelectedItem="{Binding Path=SelectedItem2,ValidatesOnDataErrors=True}"/>
</StackPanel>
是解决这个问题的更好方法。