1.从数据库中查询出的数据作为数据源
/// <summary>
/// 管理员
/// </summary>
public class AdminCombobox:ComboBoxEx
{
SysUserContext db = new SysUserContext();
public AdminCombobox()
: base()
{
if (!DesignerProperties.IsInDesignTool)
{
db.Load(db.GetAdminListQuery()).Completed += new EventHandler(AdminCombobox_Completed);
this.ItemsSource = db.SysUsers;
this.DisplayMemberPath = "UserName";
this.SelectedValuePath = "UserID";
// this.SelectedIndex = 0; 此处不能写这句,因为此时还没有返回数据
}
}
void AdminCombobox_Completed(object sender, EventArgs e)
{
//两下tab建自动生成的throw 的代码一定要去掉
if (db.SysUsers.Count > 0)
this.SelectedIndex = 0;
}
}
2.静态数据作为数据源
/// <summary>
/// 立柱数目
/// </summary>
public class BraceNumCombobox:ComboBoxEx
{
public BraceNumCombobox()
: base()
{
if (!DesignerProperties.IsInDesignTool)
{
this.ItemsSource = new List<MyType>() {
new MyType(){ ID=2, Name="2"},
new MyType(){ ID=4, Name="4"},
new MyType(){ ID=6, Name="6"}
};
this.DisplayMemberPath = "Name";
this.SelectedValuePath = "ID";
this.SelectedIndex = 0;
}
}
}
备注:MyType是自定义的一个实体类
界面中使用
<my:DistributionCombobox Height="22" x:Name="distributionCombobox1" SelectedValueProper="{Binding ZCSensor.PlacementOfThreeArea,Mode=TwoWay}"
Width="70" />数据类型一定要完全匹配,否则没法选中