我在这里坚持数据绑定。所以,假设我有以下Class
:
Student.cs
public class Student : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public string _name;
public string Name
{
get { return _name; }
set { _name = value; NotifyPropertyChanged("Name");
}
public bool _isSelected;
public bool IsSelected
{
get { return _isSelected; }
set { _isSelected = value; NotifyPropertyChanged("IsSelected");
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
然后,我有一个UserControl
可视化该类,使用以下ViewModel:
StudentVisualizerVM.cs
public class StudentVisualizerVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Student _student;
public Student Student
{
get { return _student; }
set { _student = value ; NotifyPropertyChanged("Student"); }
}
public StudentVisualizerVM()
{
Student = new Student();
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
然后,我想在MainWindow中使用UserControl。
MainWindow.Xaml
<ItemsControl Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Student}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel IsItemsHost="True"/>
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<c:StudentVisualizer/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
最后这是我的MainWindow ViewModel看起来像:
MainWindowVM.cs
public class MainWindowVM : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Student _student;
public Student Student
{
get { return _student; }
set { _student = value ; NotifyPropertyChanged("Student"); }
}
public MainWindowVM()
{
Student = new Student();
}
private void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
问题在于User Control
MainWindow
未显示Student
,即使我已在MainWindow
中初始化MVVM User Control
属性。为什么?是不是StudentVisualizerVM
会自动填充其ViewModel?或者可能MainWindowVM
我需要存储在Student
中,而不是DataContext
本身?
请注意(已更新):
StudentVisualizer
。IsSelected
之外点击,然后Student
设置为false。 (此属性用于需要选择{{1}}的某些命令。) - 类似Select-Deselect-esque actio。答案 0 :(得分:1)
ItemsControl
用于显示项目集合,因此ItemsControl.ItemsSource
必须绑定到IEnumerable
属性,而您只需绑定到单个元素。
你想要这样的东西:
ItemsSource="{Binding StudentCollection}"
public IEnumerable<Student> StudentCollection
{
get { return new List<Student> { Student }; }
}
现在,你真的应该使用ItemsControl
只显示一个项目......这是另一个问题,答案是:没有。