//調用
IniCombox(cbChannelName, typeof(Model.SystemEnum.ChannelName));
//具體實現
public void IniCombox(Relations.Control.ComBox cb, Type type)
{
cb.DisplayMember = "Description";
cb.ValueMember = "value";
List<Model.ObjectInfo> list = new List<Model.ObjectInfo>();
foreach (var inst in Enum.GetValues(type))
{
list.Add(new Model.ObjectInfo()
{
Description = GetEnumDescription(inst as System.Enum),
value = inst
});
}
cb.DataSource = list;
}
public class ObjectInfo
{
public string Description { get; set; }
public object value { get; set; }
}
public static string GetEnumDescription(Enum enumValue)
{
string _Result = string.Empty;
try
{
System.Reflection.FieldInfo _FieldInfo = enumValue.GetType().GetField(_Result);
object[] objs = _FieldInfo.GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false);
if (objs == null || objs.Length == 0) return _Result;
System.ComponentModel.DescriptionAttribute da = (System.ComponentModel.DescriptionAttribute)objs[0];
return da.Description;
}
catch
{
return string.Empty;
}
}
//以下獲取數據僅針對利用DataSource賦值有效,利用Item賦值,效果有出入
//cbGasName.SelectedText:選中的文本,用鼠標選中的情況下
//cbGasName.SelectedItem:綁定數據源中對應的對象
//cbGasName.SelectedValue:DataSource情況下:ValueMember綁定對應對象的屬性值;Item情況下,返回null;
在利用SelectedValue賦值時,若ValueMember(object)內爲對象時,無法賦值成功;
//cbGasName.Text:DisplayMember綁定對應對象的屬性值
//賦值與取值一般選取cbGasName.SelectedValue
總結:鑑於DataSource與Item賦值,均有可能出現BUG(例如:取值爲空、自動選擇第一項等問題)的情況下,建議取值(對象包含多種屬性,希望獲取值非Text顯式屬性)時,通過SelectItem獲取Object,將其轉換爲所需對象,然後拿對象的屬性。