我創建了一個winform自定義控件,它具有共享相同綁定源的文本框和列表框,以便可以使用文本框輸入過濾列表框。winform listbox drawitem更改子串顏色
我需要覆蓋lisbox drawitem,以便過濾後的項目將搜索到的文本作爲子字符串變爲不同顏色或突出顯示。 (即,)期望黃色突出顯示,如下面的示例圖像。
我做了如下
private void DrawItemHandler(object sender, DrawItemEventArgs e)
{
this.Invoke((MethodInvoker)delegate
{
e.DrawBackground();
e.DrawFocusRectangle();
string MyString = listBox.GetItemText(listBox.Items[e.Index]);
string stringToFind = searchInput.Text ;
if (!string.IsNullOrEmpty(stringToFind))
{
List<int> positions = new List<int>();
int pos = 0;
while ((pos < MyString.Length) && (pos = MyString.IndexOf(stringToFind, pos, StringComparison.InvariantCultureIgnoreCase)) != -1)
{
positions.Add(pos);
pos += stringToFind.Length;
}
int c = 0, nLen = 0, width = 0;
Rectangle rect = e.Bounds;
rect.X = width;
do
{
if (positions.Contains(c))
{
//int opacity = 128;
e.Graphics.DrawString(MyString.Substring(c, stringToFind.Length),
e.Font,
//new SolidBrush(Color.FromArgb(opacity, Color.LightYellow)),
new SolidBrush(Color.LightYellow),
rect);
nLen = MyString.Substring(c, stringToFind.Length).Length;
width += nLen;
}
else
{
e.Graphics.DrawString(MyString[c].ToString(),
e.Font,
new SolidBrush(listBox.ForeColor),
rect);
nLen = MyString[c].ToString().Length;
width += nLen;
}
rect.X = width;
}
while ((c += nLen) < MyString.Length);
}
else
{
e.Graphics.DrawString(MyString,
e.Font,
new SolidBrush(listBox.ForeColor),
e.Bounds);
}
});
}
,結果是該項目的文本是覆蓋字符。
我不能識別錯誤的部分,它是在矩形範圍或束帶的部分。除了項目背景顏色之外,如何更改項目文本中子字符串的背景。請幫助我。
要更改子的研究背景,我懷疑你必須首先使用FillRectangle,然後的DrawString在該矩形 – Pikoh
要使用自定義背景色使用TextRenderer而不是DrawString!您前進rectangle.X的方法是使用字符串中的字符長度而不是像素長度。使用Graphics.MeasureString(... Typographics)查找高亮部分的寬度。 – TaW
嘗試使用FillRectangle建議的MeasureString,我可以看到差異,但仍然需要調整。多謝你們。 – madmonk88