我是绑定和WPF方面的新手,最近我学会了如何使用绑定技术创建具有多个列的listBox
<ListView ItemsSource="{Binding Items}" Margin="306,70,22,17" MouseDoubleClick="listBoxSS_MouseDoubleClick" Name="listBoxSS" >
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="first_name " Width="100" DisplayMemberBinding="{Binding Path=First_name}" />
<GridViewColumn Header="last_name" Width="100" DisplayMemberBinding="{Binding Path=Last_name}" />
<GridViewColumn Header="phone_number" Width="100" DisplayMemberBinding="{Binding Path=Phones[0]}" />
<GridViewColumn Header="notes" Width="100" 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,70,22,17" MouseDoubleClick="listBoxSS_MouseDoubleClick" Name="listBoxSS" >
<ListView.View>
<GridView>
<GridView.Columns>
<GridViewColumn Header="first_name " Width="100" DisplayMemberBinding="{Binding Path=First_name}" />
<GridViewColumn Header="last_name" Width="100" DisplayMemberBinding="{Binding Path=Last_name}" />
<GridViewColumn Header="phone_number" Width="100" DisplayMemberBinding="{Binding Path=Phones[0]}" />
<GridViewColumn Header="notes" Width="100" 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);
每当我在Gemployees!!中添加或删除项目时,ListView
都会执行刷新虽然很酷,但在绑定方面还是有些困难。现在我正在为每个ListView创建一个接口类,这样我就可以把我的东西放进去了。在添加项目时,它不会执行任何灵活性。
发布于 2012-06-19 03:32:21
您将ItemsSource
绑定到DataContext
中名为Items
的属性,因此要更新集合,需要转到DataContext
中的Items
属性并清除它。
此外,如果希望Items
属性在基础集合更改时更新UI,则该属性的类型必须为ObservableCollection
,而不是List
。
您不需要在后台代码中设置ItemsSource
的代码,应该将其删除。您只需要在一个位置设置ItemsSource
,而不是在两个位置都设置。
下面是一个简单的示例,说明它是如何工作的:
// Using Students instead of Items for the PropertyName to clarify
public ObservableCollection<Student> Students { get; set; }
public MyConstructor()
{
...
Students = search.students();
listBoxSS.DataContext = this;
}
现在,当您拥有以下内容时:
<ListView ItemsSource="{Binding Students}" ... />
您正在将ItemsSource
绑定到ObservableCollection<Student>
,当您想要清除列表时,您可以调用:
Students.Clear()
发布于 2014-06-01 17:21:58
我知道这个问题大约在2年前就得到了回答,但是我自己也有这个问题,我自己也想了一个可能的解决方案,它是有效的。也许这在某些场景下不起作用,也许我只是没有看到什么,但它对我很有效,所以我在这里分享它:
listView.ClearValue(ItemsControl.ItemsSourceProperty);
listView.ItemsSource = NewSource;
我真心希望这对某些人有帮助。
发布于 2014-06-14 03:35:13
奇怪但却是真的:我的XAML文件中的以下错误击键产生了错误“操作在使用ItemsSource时无效。请改为使用ItemsControl.ItemsSource访问和修改元素。”:
</ItemsControl.ItemTemplate>x`
注意结束元素标签后面的"x`“字符。
https://stackoverflow.com/questions/11089104
复制相似问题