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>

 

 界面效果:


 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM