今天用到了ComboBox控件,像往常一样根据以往使用WebForm的DropDownlist或者WinForm中ComboBox控件的经验来使用Silverlight的ComboBox控件,
可是遇到麻烦了。
为ComboBox绑定了某个列表,然后需要根据我当前的值去指定ComboBox的当前选择项。比如说ComboBox绑定了一个List<Employee>.
1 List<Employee> list = new List<Employee>(){
2 new Employee(){ EmpID="111", EmpName="1ssssss"},
3 new Employee(){EmpID="222",EmpName="2dddd"},
4 new Employee(){EmpID="333",EmpName="3ffff"}
5 };
6 this.comboBox1.ItemsSource = list;
7 this.comboBox1.DisplayMemberPath = "EmpName";
2 new Employee(){ EmpID="111", EmpName="1ssssss"},
3 new Employee(){EmpID="222",EmpName="2dddd"},
4 new Employee(){EmpID="333",EmpName="3ffff"}
5 };
6 this.comboBox1.ItemsSource = list;
7 this.comboBox1.DisplayMemberPath = "EmpName";
现在希望把ID为333的Employee设为当前选择项。不能像以前那样直接Text="3ffff"设定当前值。
在Siverlight中却有些繁琐。具体的代码:
Employee emp = new Employee() { EmpID = "333", EmpName = "3ffff" }; //this.comboBox1.SelectedItem = emp; //这样设不起作用.
List<Employee> list = this.comboBox1.ItemsSource as List<Employee>;
int flag = -1;
for (int i = 0; i < list.Count; i++)
{
if (list[i].EmpID == emp.EmpID && list[i].EmpName == emp.EmpName)
{
flag = i;
break;
}
}
this.comboBox1.SelectedIndex = flag;
List<Employee> list = this.comboBox1.ItemsSource as List<Employee>;
int flag = -1;
for (int i = 0; i < list.Count; i++)
{
if (list[i].EmpID == emp.EmpID && list[i].EmpName == emp.EmpName)
{
flag = i;
break;
}
}
this.comboBox1.SelectedIndex = flag;
到此为止,可以设置ComboBox的当前选择项了。是不是有些绕,为什么不能直接公开一个属性让开发者去设呢?
完整代码:
C#
XAML
原创贴,自娱自乐的同时,也为大家带来帮助 。