Silverlight中为ComboBox设定当前选择项、数据绑定、取值。

public partial class Page : UserControl
 {
  public Page()
  {
   // 需要初始化变量
   InitializeComponent();
            
          Cmbs_Items_Add();
  }

      public class CombItem
        {
            public string Value
            {
                get;
                set;
            }

            public string Text
            {
                get;
                set;
            }


        }

        /// <summary>
        /// 给combox赋值
        /// </summary>
        private void Cmbs_Items_Add()
        {
            //给 房屋标识 赋值
            this.cmbs.UpdateLayout();//设置this.cmbs.UpdateLayout();确保 UIElement 的所有子对象位置都正确地进行了布局更新
            List<CombItem> ctg = new List<CombItem>()
            {
                new CombItem { Value="", Text="" },
                new CombItem { Value="0", Text="正常" },
                new CombItem { Value="1", Text="新增" },
                new CombItem { Value="2", Text="已拆" }
            };


            this.cmbs.ItemsSource = ctg;
            cmbs.DisplayMemberPath = "Text";//绑定Text值
            this.cmbs.SelectedValuePath = "Value";//指定Value值
        }





       #region ========设定当前选择项========
            CombItem emp = new CombItem() { Value = "", Text = "" };                                                                              //this.comboBox1.SelectedItem = emp;  //这样设不起作用.
            List<CombItem> list = this.cmbs.ItemsSource as List<CombItem>;
            int flag = -1;
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i].Value == emp.Value && list[i].Text == emp.Text)
                {
                    flag = i;
                    break;
                }
            }
            this.cmbs.SelectedIndex = flag;
            #endregion

//获取combox选中的值
CombItem emp = this.cmbs.SelectedItem as CombItem;

}
posted on 2012-11-09 13:00  小东北  阅读(2463)  评论(0编辑  收藏  举报