1. 程式人生 > >WPF的ComboBox資料繫結,使用Dictionary作為資料來源

WPF的ComboBox資料繫結,使用Dictionary作為資料來源

ViewModel
//屬性定義
     Dictionary<int, string> _selGroupList;
        /// <summary>
        /// 分組下拉列表
        /// </summary>
        public Dictionary<int, string> selGroupList
        {
            get { return _selGroupList; }
            set
            {
                _selGroupList = value;
                NotifyOfPropertyChange("selGroupList");
            }
        }
        private int _Group;
        /// <summary>
        ///當前分組
        /// </summary>
        public int Group
        {
            get { return _Group; }
            set
            {
                _Group = value;
                NotifyOfPropertyChange(() => Group);
            }

        }

//初始化資料
 //介面資料
  public ModuleInfoViewModel(sys_Right_Module groupInfo, OperType type)
{
       GetGroupList();
       Group = groupInfo.GroupID;
}
 /// <summary> 
/// 初始化分組下拉資料
 /// </summary>
 public void GetGroupList()
 { 
Dictionary<int, string> dic = new Dictionary<int, string>();
 dic.Add(-1, "=請選擇=");
 List<sys_Right_Group> groupList = DataBaseService.DataBaseServer<sys_Right_Group>.GetModelList(" IsActive=1 ");
 if (groupList != null)
 { 
  groupList.ForEach(x => 
  { 
    dic.Add(x.GroupID, x.GroupName); });
  } 
selGroupList = dic; 
Group = -1; //預設選中第一項 
}

View介面繫結:

ItemsSource資料來源為字典資料
DisplayMemberPath="Value" 為顯示字典資料的值
SelectedValuePath="Key"字典資料的鍵與SelectedValue型別對應
                <ComboBox Grid.Row="8" Grid.Column="1" ItemsSource="{Binding selGroupList}" SelectedIndex="0"  SelectedValuePath="Key" DisplayMemberPath="Value" SelectedValue="{Binding Group,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}
" HorizontalAlignment="Left" Width="252" Height="25" IsEditable="True" Margin="5,3"></ComboBox>

 介面效果:

念念不忘,必有迴響。技術成就夢想!