我的XAML中有一个ComboBox和一个DataGrid:
<ComboBox SelectedItem="{Binding SelectedFamily}" ItemsSource="{Binding FamilyList}" IsSynchronizedWithCurrentItem="True"/>
<DataGrid ItemsSource="{Binding FamilyInfoGrid}" AutoGenerateColumns="False">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Age" Binding="{Binding Age}" />
</DataGrid.Columns>
</DataGrid>
这是我的viewmodel:
public class MainWindowViewModel : INotifyPropertyChanged
{
private ReadOnlyObservableCollection<Family> _familyList;
public ReadOnlyObservableCollection<Family> FamilyList
{
get { return _familyList; }
}
private Family _selectedFamily;
public Family SelectedFamily
{
get
{
return _selectedFamily;
}
set
{
_familyInfoGrid.Clear();
_familyInfoGrid.Add(value.Kid);
_familyInfoGrid.Add(value.Parent2);
_familyInfoGrid.Add(value.Parent1);
RaisePropertyChangedEvent();
}
}
private ObservableCollection<Person> _familyInfoGrid = new ObservableCollection<Person>();
public ObservableCollection<Person> FamilyInfoGrid
{
get { return _familyInfoGrid; }
set { _familyInfoGrid = value; RaisePropertyChangedEvent(); }
}
public MainWindowViewModel()
{
var fam1 = new Family("Smith", new Person("Jim", 31), new Person("Eve", 29), new Person("Tom", 2));
var fam2 = new Family("Miller", new Person("Joe", 35), new Person("Sue", 33), new Person("Kim", 8));
_familyList = new ReadOnlyObservableCollection<Family>(new ObservableCollection<Family>() { fam1, fam2 } );
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChangedEvent([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
这意味着DataGrid总是更新到组合框的当前所选项目 - 应该如此。
这是我的模特:
public class Family
{
public string Name { get; set; }
public Person Kid { get; set; }
public Person Parent1 { get; set; }
public Person Parent2 { get; set; }
public Family(string name, Person parent1, Person parent2, Person kid)
{
Name = name; Parent1 = parent1; Parent2 = parent2; Kid = kid;
}
public override string ToString()
{
return Name;
}
}
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age)
{
Name = name; Age = age;
}
}
问题是在DataGrid中进行的更改存储在_familyList中,但我希望_familyList是不可变的,并且只能暂时编辑(和使用)DataGrid的当前字段(所以{{1也不是一个选项。)
答案 0 :(得分:0)
感谢@ mm8我设法找到了解决方案。组合框中当前选定的项目必须是&#34;深度复制&#34;:
public Family SelectedFamily
{
set
{
var fam = new Family(
new string(value.Name.ToCharArray()),
new Person(value.Parent1.Name, value.Parent1.Age),
new Person(value.Parent2.Name, value.Parent2.Age),
new Person(value.Kid.Name, value.Kid.Age));
_familyInfoGrid.Clear();
_familyInfoGrid.Add(fam.Kid);
_familyInfoGrid.Add(fam.Parent2);
_familyInfoGrid.Add(fam.Parent1);
RaisePropertyChangedEvent();
}
}