我想從一個文本文件中添加一個計算機列表到一個列表框,並根據計算機上的ping是否成功,它應該爲綠色成功或紅色失敗。問題在於它使用所有項目上最後一臺計算機的最後一種顏色。我相信這是因爲在for循環完成之前Drawitem事件不會被提出,但我想不出一個辦法解決這個問題。任何幫助表示讚賞。 (針對ping的縮減代碼)如何添加具有特定文本顏色的列表框項目?
private logitem linez;
struct logitem
{
public string text;
public Brush color;
};
private void browsebutton_Click(object sender, EventArgs e)
{
string textfile = ofd.FileName;
if (textfile != "")
{
string[] lines = System.IO.File.ReadAllLines(@textfile);
foreach (string line in lines)
{
if (line != "")
{
string liner;
liner = line.Replace(" ", "");
if (ping successfull)
{
listBoxAddGreen();
}
else (ping fails)
{
listBoxAddRed();
}
}
changeCount();
}
}
public void listBoxAddGreen()
{
linez.color = Brushes.Green;
listBox1.Items.Add(linez.text);
}
public void listBoxAddRed()
{
linez.color = Brushes.Red;
listBox1.Items.Add(linez.text);
}
private void listBox1_DrawItem(object sender,
System.Windows.Forms.DrawItemEventArgs e)
{
e.DrawBackground();
Brush myBrush = linez.color;
e.Graphics.DrawString(listBox1.Items[e.Index].ToString(),
e.Font, myBrush, e.Bounds, StringFormat.GenericDefault);
e.DrawFocusRectangle();
}
你打算使用'ListView'嗎?更換顏色更容易。 –
你有繪製模式設置爲'OwnerDrawnFixed'嗎? –
你必須**熟悉MVVM。使用它你的任務將在幾分鐘內解決。 1)在視圖模型中進行ping操作; 2)每個ping項目都應該有它的視圖模型(例如'ItemVM')和'PingOk'屬性來顯示ping是否成功; 3)將'ListBox'的'ItemsSource'綁定到'ItemVM'的集合; 4)根據「PingOk」屬性的值在''ListBoxItem''的XAML中設置觸發器來改變'Foreground'。對於你的任務,「ListBox」比ListView更有用,因此堅持使用這個項目控件。 – Maxim