我之前曾询问过有关我与复选框绑定(bind)的问题。终于向前迈出了一步! :) 现在,我想知道以下事情:我有一个名为 SelectedCourses 的集合,它存储复选框中选中的所有类(class)。我的问题是,当我检查 2 个或更多类(class)时,它只存储列表中的第一个值,即使我在另一个值之后选择了它。我用于存储值的代码如下所示:
public void SaveTeacher(object param)
{
using (DatabaseStudentsEntitiesLastStand db = new DatabaseStudentsEntitiesLastStand())
{
Cours c = new Cours();
RegisterTeacher t = new RegisterTeacher();
if (c.IsChecked == true)
{
foreach(var item in Courses)
{
if(item.IsChecked)//here IsChecked is true
{
SelectedCourses = new ObservableCollection<Cours>();
SelectedCourses.Add(item);//here I have only one course
}
SelectedCourses.ToList();
}
}
t.SNTeacher = SNTeacher;
t.UserName = _UserName;
t.pwd = pwd;
t.fullName = fullName;
t.education = education;
db.RegisterTeachers.Attach(t);
try
{
db.SaveChanges();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
我的收藏是这样的:
private ObservableCollection<Cours> selectedCourses;
public ObservableCollection<Cours> SelectedCourses
{
get { return selectedCourses; }
set
{
selectedCourses = value;
NotifyOnPropertyChange("SelectedCourses");
}
}
我还有一个包含所有类(class)的集合:
private ObservableCollection<Cours> _courses;
public ObservableCollection<Cours> Courses
{
get => _courses;
set
{
_courses = value;
NotifyOnPropertyChange(nameof(Courses));
}
}
这是我的系统的外观以及检查 2 个值的示例:
这就是我设置断点时得到的:
如您所见,SelectedCourses 中只添加了一门类(class)。我怎样才能让它保存与用户检查一样多的类(class)?
最后但并非最不重要的是,与 .xaml 的绑定(bind):
<ListBox x:Name="coursesList" SelectedItem="{Binding SelectedCourses}"
HorizontalAlignment="Left" Margin="538,23.2,0,0" Grid.Row="2"
VerticalAlignment="Top" Width="225" ItemsSource="{Binding Courses}" Height="255" Grid.RowSpan="2" >
<ListBox.ItemTemplate>
<DataTemplate>
<ListBoxItem IsSelected="{Binding IsChecked}">
<CheckBox x:Name="CheckBoxList" Content="{Binding Path=courseName}" IsChecked="{Binding Path=IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"/>
</ListBoxItem>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
最佳答案
在您的代码中,您正在创建一个新的 ObservableCollection
在每次迭代中。
试试这样:
if (c.IsChecked == true)
{
SelectedCourses = new ObservableCollection<Cours>();
foreach(var item in Courses)
{
if(item.IsChecked)//here IsChecked is true
{
SelectedCourses.Add(item);//here I have only one course
}
}
}
关于c# - 如果检查了 2 个或更多值,为什么我只有一个值存储在集合中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49895033/