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>
界面效果: