我需要帮助解决以下问题:
我有一个有两个属性的类。
private byte m_selectedValue;
public byte SelectedValue
{
get { return m_selectedValue; }
set { m_selectedValue = value; }
}
private string[] m_possibleValues;
public string[] PossibleValues
{
get { return m_possibleValues; }
set { m_possibleValues = value; }
}
PossibleValues 存储可选值的列表。SelectedValue 包含实际选择值的索引。
在这种状态下,属性编辑器显示所选值的索引。我想使用属性网格中的组合框选择值,与 Enum 属性使用的样式相同。组合框的列表将从 PossibleValues 属性中填充。
在这篇文章的帮助下(http://www.codeproject.com/KB/cpp/UniversalDropdownEditor.aspx)我设法创建了一个自定义编辑器,该编辑器在属性网格上显示组合框,其中包含来自 PossibleValues 属性的值。我也可以选择值,但属性网格仍然显示值的索引而不是值本身。
这是编辑器修改后的源码(原文来自 CodeProject):
public class EnumParamValuesEditor : UITypeEditor
{
private IWindowsFormsEditorService edSvc;
public override UITypeEditorEditStyle GetEditStyle(System.ComponentModel.ITypeDescriptorContext context)
{
if ((context != null) && (context.Instance != null))
return UITypeEditorEditStyle.DropDown;
return UITypeEditorEditStyle.None;
}
public override object EditValue(System.ComponentModel.ITypeDescriptorContext context, IServiceProvider provider, object value)
{
if ((context == null) || (provider == null) || (context.Instance == null))
return base.EditValue(provider, value);
edSvc = (IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (edSvc == null)
return base.EditValue(provider, value);
ListBox lst = new ListBox();
PrepareListBox(lst, context);
lst.SelectedIndex = (byte)value;
edSvc.DropDownControl(lst);
if (lst.SelectedItem == null)
value = null;
else
value = (byte)lst.SelectedIndex;
return value;
}
private void PrepareListBox(ListBox lst, ITypeDescriptorContext context)
{
lst.IntegralHeight = true;
string[] coll = ((EnumTerminalParam)context.Instance).PossibleValues;
if (lst.ItemHeight > 0)
{
if ((coll != null) && (lst.Height / lst.ItemHeight < coll.Length))
{
int adjHei = coll.Length * lst.ItemHeight;
if (adjHei > 200)
adjHei = 200;
lst.Height = adjHei;
}
}
else
lst.Height = 200;
lst.Sorted = true;
FillListBoxFromCollection(lst, coll);
lst.SelectedIndexChanged += new EventHandler(lst_SelectedIndexChanged);
}
void lst_SelectedIndexChanged(object sender, EventArgs e)
{
if (edSvc == null)
return;
edSvc.CloseDropDown();
}
public void FillListBoxFromCollection(ListBox lb, ICollection coll)
{
lb.BeginUpdate();
lb.Items.Clear();
foreach (object item in coll)
lb.Items.Add(item);
lb.EndUpdate();
lb.Invalidate();
}
}
当然,它需要进一步修改才能正确处理某些情况(例如,PossibleValues 为空)。
那么是否可以在属性编辑器中显示 PossibleValues[SelectedValue] 而不是 SelectedValue?