使用ItemsSource时操作无效改为使用ItemsControl.ItemsSource访问和修改元素

浏览:52日期:2024-03-16
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解决使用ItemsSource时操作无效改为使用ItemsControl.ItemsSource访问和修改元素?

你绑定ItemsSource在一个属性DataContext叫Items,所以要更新集合,你需要去Items的财产DataContext和清除。

另外,该Items属性的类型必须为ObservableCollection,List如果您希望在基础集合发生更改时更新UI ,则不需要。

您ItemsSource不需要在后面的代码中设置代码的位,因此应将其删除。您只需要将其设置ItemsSource在一个位置,而不是两个都设置。

这是一个如何工作的简单示例:

// Using Students instead of Items for the PropertyName to clarifypublic ObservableCollection<Student> Students { get; set; }public MyConstructor(){ ... Students = search.students(); listBoxSS.DataContext = this;}

现在,当您拥有:

<ListView ItemsSource='{Binding Students}' ... />

您将绑定ItemsSource到ObservableCollection<Student>,并且要清除列表时可以调用:

Students.Clear()解决方法

我是Binding和WPF的新手,我已经学习了如何listBox使用Binding技术创建具有多列的

<ListView ItemsSource='{Binding Items}' Margin='306,70,22,17' MouseDoubleClick='listBoxSS_MouseDoubleClick' Name='listBoxSS' > <ListView.View> <GridView><GridView.Columns> <GridViewColumn Header='first_name ' DisplayMemberBinding='{Binding Path=First_name}' /> <GridViewColumn Header='last_name' DisplayMemberBinding='{Binding Path=Last_name}' /> <GridViewColumn Header='phone_number' DisplayMemberBinding='{Binding Path=Phones[0]}' /> <GridViewColumn Header='notes' DisplayMemberBinding='{Binding Path=Notes}' /></GridView.Columns> </GridView></ListView.View> </ListView>

这是代码:

List<Student> arr = search.students();listBoxSS.ItemsSource = arr;

但是问题是当我尝试使用添加或删除项目或清除时

listBoxSS.Items.Clear();

请提供使用物品来源或添加,删除物品或清除列表的方式的示例。

编辑:

<ListView ItemsSource='{Binding Items}' Margin='306,17' MouseDoubleClick='listBoxSS_MouseDoubleClick' Name='listBoxSS' > <ListView.View><GridView> <GridView.Columns><GridViewColumn Header='first_name ' DisplayMemberBinding='{Binding Path=First_name}' /><GridViewColumn Header='last_name' DisplayMemberBinding='{Binding Path=Last_name}' /><GridViewColumn Header='phone_number' DisplayMemberBinding='{Binding Path=Phones[0]}' /><GridViewColumn Header='notes' DisplayMemberBinding='{Binding Path=Notes}' /> </GridView.Columns></GridView> </ListView.View></ListView>

这是代码:

ObservableCollection<Employee> Gemployees;var employees = new ObservableCollection<Employee>(search.employees());

search.employees() 获取我数据库中所有员工的列表

listBoxPE.ItemsSource = employees;Gemployees = employees;

现在我可以对Gemployees执行所有方法

Gemployees.Remove((Student)listBoxSS.SelectedItem); Gemployees.Add((Student)listBoxSS.SelectedItem);

该ListView每当我添加或删除Gemployees的项目进行刷新!很酷,但在绑定方面仍然有些艰苦。现在,我正在为每个ListView做一个接口类,以便可以将其放入其中。它不会在添加项目中表现出任何灵活性。

相关文章: