亲爱的StackOverflow用户。我有一个任务:我有一个从JSON获得的学生列表。
[
{
"Name": "Grant",
"Groupname": "Group1"
},
{
"Name": "Tim",
"Groupname": "Group2"
},
{
"Name": "Spencer",
"Groupname": "Group3"
}
.....
]
然后,我有两个列表框:第一个用于组,第二个用于属于该组的学生。我无法解决的问题:使用Binding和DataContext在listBox中显示当前选定组的学生。所以我需要帮助。学生和团体的声明:
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public string Groupname { get; set; }
}
public class Group
{
public string Name { get; set; }
public int Count { get; set; } // how many students are in this group
public List<Student> Students = new List<Student>();
public Group()
{
}
public Group(string name, int count)
{
this.Name = name;
this.Count = count;
}
}
下面的代码使用“小组列表”,每个小组都有一个学生列表。而在这一刻,我被困住了。
public MainWindow()
{
List<Group> groups = new List<Group>();
// I excluded json deserialization and Lists initialization code...
InitializeComponent();
foreach (var x in groups)
{
GroupsView.Items.Add(x.Name);
foreach (var y in x.Students)
{
StudentsView.Items.Add(y);
}
}
}
XAML中的listBoxes
<ListBox Name="GroupsView" HorizontalAlignment="Left" Height="172" Margin="48,0,0,0" VerticalAlignment="Center" Width="206"/>
<ListBox Name="StudentsView" HorizontalAlignment="Left" Height="172" Margin="306,0,0,0" VerticalAlignment="Center" Width="364">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock>
<Run Text="{Binding Path=Id}"></Run>
<Run Text="{Binding Path=Name}"></Run>
</TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
我知道它与XAML有关,但是我突然遇到了这个问题,需要尽快完成。上一次我在2017年使用C#时,请原谅我这个愚蠢的问题。如果有人可以帮忙,我将非常感激
public class MainWindow : INotifyPropertyChanged
并在构造函数中添加: this.DataContext = this;
private List<Group> _groups;
public List<Group> Groups
{
get { return _groups; }
set { _groups = value; OnPropertyChanged(); }
}
private Group _selectedGroup;
public Group SelectedGroup
{
get { return _selectedGroup; }
set
{
_selectedGroup = value;
OnPropertyChanged();
if (_selectedGroup != null)
{
Students = _selectedGroup.Students;
}
}
}
private List<Student> _students;
public List<Student> Students
{
get { return _students; }
set { _students = value; OnPropertyChanged(); }
}
<ListBox ItemsSource=”{Binding Groups}” SelectedItem=”{Binding SelectedGroup}” … />
<ListBox ItemsSource=”{Binding Students}” … />
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句