[英]How to create a property to store the index of the selected value from another property?
我需要以下問題的幫助:
我有一個有兩個屬性的類。
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嗎?
您需要將自定義TypeConverter附加到SelectedValue屬性,並使PossibleValues不可瀏覽。 TypeConverter將負責在PropertyGrid中顯示字符串而不是int。 所以基本上,你需要覆蓋CanConvertFrom,CanConvertTo,ConvertFrom和ConvertTo。 如果要獲取自定義字符串,請使用傳遞給這些方法的context參數,並在目標實例中調用PossibleValues屬性。 那應該成功。 看來你這里不需要任何自定義UITypeEditor。
而不是兩個單獨的屬性,為什么不在Dictionary類型中將它們綁定在一起。 在這種情況下使用起來更加容易。 將索引作為鍵,將字符串[]作為值。 只是不要將自己限制為索引的一個字節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.