MVVM模式WPF的ComboBox数据绑定,使用Dictionary作为数据源
ViewModel
//属性定义 Dictionary<int, string> _selGroupList; ////// 分组下拉列表 /// public Dictionary<int, string> selGroupList { get { return _selGroupList; } set { _selGroupList = value; NotifyOfPropertyChange("selGroupList"); } } private int _Group; /// ///当前分组 /// public int Group { get { return _Group; } set { _Group = value; NotifyOfPropertyChange(() => Group); } }
//初始化数据 //界面数据 public ModuleInfoViewModel(sys_Right_Module groupInfo, OperType type) { GetGroupList();
Group = groupInfo.GroupID;
}
///
/// 初始化分组下拉数据
///
public void GetGroupList()
{
Dictionary<int, string> dic = new Dictionary<int, string>();
dic.Add(-1, "=请选择=");
ListgroupList = DataBaseService.DataBaseServer .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类型对应
"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">
界面效果: