我创建了一个自定义组合框,其中我可以在ComboBox下拉时显示多列项目和图像。现在我遇到的问题是当选择一个项目时,我需要完全按照下拉列表中显示的项目显示项目,即。那么我应该参加哪个活动?或者我怎样才能做到这一点?
到目前为止,我有这个
public partial class XComboBox : ComboBox
{
private Int32 ColumnGap = 10;
private Int32 firstColumnWidth;
private Int32 secondColumnWidth;
public XComboBox()
{
DrawMode = DrawMode.OwnerDrawFixed;
firstColumnWidth = DropDownWidth / 2;
secondColumnWidth = DropDownWidth / 2;
AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
}
public Boolean MultiColumn
{
get;
set;
}
public String ColumnWidths
{
get
{
return String.Concat(firstColumnWidth.ToString(), ";", secondColumnWidth.ToString());
}
set
{
if (Regex.Match(value, "^[0-9]+;[0-9]+$").Success)
{
String[] widths = value.Split(';');
firstColumnWidth = Int32.Parse(widths[0]);
secondColumnWidth = Int32.Parse(widths[1]);
DropDownWidth = (firstColumnWidth + secondColumnWidth + ColumnGap) > Width ? (firstColumnWidth + secondColumnWidth + ColumnGap) : Width;
}
else
{
throw new ArgumentException("Invalid argument specified. Value of ColumnWidths property should be in \"[0-9];[0-9]\" format");
}
}
}
protected override void OnDrawItem(DrawItemEventArgs e)
{
XComboItem item = (XComboItem)Items[e.Index];
ColumnGap = firstColumnWidth == 0 ? 0 : ColumnGap;
e.DrawBackground();
e.DrawFocusRectangle();
string first = item.DisplayName;
string second = item.Description;
if (MultiColumn)
{
while (TextRenderer.MeasureText(first, e.Font).Width > firstColumnWidth)
{
first = first.Substring(0, first.Length - 1);
}
e.Graphics.DrawString(first, e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left, e.Bounds.Top);
e.Graphics.DrawString(second, e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left + firstColumnWidth + ColumnGap, e.Bounds.Top);
}
else
{
e.Graphics.DrawString(second, e.Font, new SolidBrush(e.ForeColor), e.Bounds.Left, e.Bounds.Top);
}
}
protected override void OnMeasureItem(MeasureItemEventArgs e)
{
base.OnMeasureItem(e);
}
protected override void OnSelectedValueChanged(EventArgs e)
{
base.OnSelectedValueChanged(e);
}
}
public class XComboItem
{
public Int32 ItemId { get; set; }
public String DisplayName { get; set; }
public Object Value { get; set; }
public String Description { get; set; }
public XComboItem()
{
DisplayName = String.Empty;
Description = String.Empty;
DisplayText = String.Empty;
}
internal String DisplayText
{
get;
set;
}
public override string ToString()
{
return DisplayName;
}
}
答案 0 :(得分:0)
我假设您不希望用户输入 - 给定格式。为此,您需要设置DropDownStyle == DropDownList
。 ..并且您当前的代码应该可以正常工作。
为下拉和下方的编辑/文本框部分调用OnDrawItem。
如:https://stackoverflow.com/a/5111692/631687中所述,您可以区分正在呈现的内容。