public partial class Page : UserControl
{
public Page()
{
// 需要初始化变量
InitializeComponent();
this.myCbb.UpdateLayout();
this.myCbb.SelectedIndex = 0;
}
public class Category
{
public int ID
{
get;
set;
}
public string Name
{
get;
set;
}
public int Count
{
get;
set;
}
}
void UserControl_Loaded(object sender, RoutedEventArgs e)
{
List<Category> ctg = new List<Category>()
{
new Category { ID=1, Name="成都", Count=028 },
new Category { ID=2, Name="乐山", Count=0833 },
new Category { ID=3, Name="北京", Count=010 },
new Category { ID=4, Name="重庆", Count=023 }
};
this.myCbb.ItemsSource = ctg;
}
private void myCbb_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Category cgy = this.myCbb.SelectedItem as Category;
this.tblInfo.Text = "你选择的地区是:" + cgy.Name + " 区号为:" + cgy.Count;
}
}
}
this.myCbb.Items.Insert(0, new ListItem("请选择...", "0"));
不行你在看看这个.
http://hi.baidu.com/%CB%B3%C6%E4%B5%C0/blog/item/8d1aa5f4d19c84d1f2d3850e.html
额…… 实际上你设置索引为0的代码是在构造函数里面,这个时候你的ComboBox里面还没有项,因为UserControl_Loaded事件还没有被引发,所以即使是索引0也是超出有效范围的。应该把 this.myCbb.UpdateLayout();
this.myCbb.SelectedIndex = 0;
放在UserControl_Loaded里面,数据绑定之后,也就是 this.myCbb.ItemsSource = ctg; 之后