Silverlight中的ComBox控件功能类似.NET中的DropDownList控件,但是用法上又是于DropDownList有点区别.
譬如,我们要做一个年份的下拉框,数据源我们通过一个类来实例化实现。
1、新建一个类
using System; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace TileViewAnimation.Component { public class Year { public string SYear { get; set; } } }
2、在MainPage.xaml页面中拖入ComBox控件,在构造函数中实例化并进行绑定绑定。
//年份数据源 List<Year> years = new List<Year>() { new Year(){ SYear="2008"},new Year(){ SYear="2009"},new Year(){ SYear="2010"},new Year(){ SYear="2011"},new Year(){ SYear="2012"},new Year(){ SYear="2013"},new Year(){ SYear="2014"},new Year(){ SYear="2015"},new Year(){ SYear="2016"},new Year(){ SYear="2017"} };
3、数据绑定和显示成员设置
this.cbstart_year.ItemsSource = years; this.cbstart_year.displayMemberPath = "SYear";
4、获取当前年份,并让当前年份处于被选中状态
//根据实际时间进行下拉框数据的绑定 string year = System.DateTime.Now.Year.ToString(); //年份索引 int index_year = -1; for (int i = 0; i < years.Count; i++) { if (years[i].SYear == year) index_year = i; } this.cbstart_year.Selectedindex = index_year;