日期:2014-05-20  浏览次数:20830 次

wpf绑定checkbox然后得到选择的集合
对ItemsControl类型的控件(如ListBox,ListView,DataGrid...)绑定数据源,想要显示一列checkbox,然后得出勾选的对象集合。


public class Staff
{
  public int ID { get; set; }
  public string Name { get; set; }
  public int Age { get; set; }
}

List<Staff> ss = new List<Staff>() 
{
  new Staff(){ ID=1, Name="s1", Age=23},
  new Staff(){ ID=2, Name="s2", Age=33},
  new Staff(){ ID=3, Name="s3", Age=29},
};
  this.listBox1.ItemsSource = ss;
  this.listBox1.DisplayMemberPath = "Name";

Staff并不存在一字段用于绑定是否勾选(假设不能改造class Staff),如果勾选ID为1,3,用什么方法才能知道哪些对象被选中了?


------解决方案--------------------
最笨的方法,轮询,如果checkbox为true,就会找到保存当前对象。当然如果有属性绑定,最好了。
//轮询listBox1
for(listbox s in listBox1)
{
  //如果选中就保存
  if(listBox1.checkbox==true)
   {
      save(s);
    }  
}