[英]change color item listbox c#
I have created a ListBox
to which I add elements during code compilation.我创建了一个
ListBox
,我在代码编译期间向其中添加了元素。 and I want to record its color when adding one element (so that each added element has a different color)我想在添加一个元素时记录它的颜色(这样每个添加的元素都有不同的颜色)
listBox1.Items.Add(string.Format("Місце {0} | В роботі з {1} | ({2} хв)", temp[7].Substring(6, 4), temp[8].Substring(11, 5), rezult)); `
I tried everywhere possible to embed this change我尽一切可能嵌入此更改
BackColor = Color.Yellow;ForeColor = Color.Yellow;
I am working with listbox because I have seen so many answers about ListView
.我正在使用列表框,因为我看到了很多关于
ListView
的答案。
Set the listbox DrawMode to either OwnerDrawFixed or OwnerDrawVariable and set this as the DrawItem event handler:将列表框 DrawMode 设置为 OwnerDrawFixed 或 OwnerDrawVariable 并将其设置为 DrawItem 事件处理程序:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e){
if(e.Index == 1) e.DrawBackground(); //use e.Index to see if we want to highlight the item
else e.Graphics.FillRectangle(new SolidBrush(Color.Yellow), e.Bounds); //This does the same thing as e.DrawBackground but with a custom color
e.DrawFocusRectangle();
if(e.Index < 0) return;
TextRenderer.DrawText(e.Graphics, (string)listBox1.Items[e.Index], listBox1.Font, e.Bounds, listBox1.ForeColor, TextFormatFlags.Left);
}
Well, best idea I have is to not use list box, but flowLayoutPanel and add usercontrols where you will have labels.好吧,我最好的想法是不使用列表框,而是使用flowLayoutPanel并在您将有标签的地方添加用户控件。
flowLayoutPanel
works as list of controls which you can scroll, so we will just create a usercontrol
, where we will put label and change the usercontrol
background Don't forget to turn on the AutoScroll
feature to flowLayoutPanel
, otherwise the scroll bar wont work and wont even show up. flowLayoutPanel
用作可以滚动的控件列表,所以我们将只创建一个usercontrol
,我们将在其中放置 label 并更改usercontrol
背景不要忘记打开AutoScroll
的自动滚动flowLayoutPanel
,否则滚动条将无法工作并且不会甚至出现。
If you want to be able to be clickable just add to the label click event.如果您希望能够点击,只需添加到 label 点击事件即可。
public void CreateItem(Color OurColor, string TextToShow)
{
Label OurText = new Label()
{
Text = "TextToShow",
Font = new Font("Segoe UI", 8f),
Location = new Point(0, 0),
AutoSize = true,
};
UserControl OurUserControl = new UserControl();
OurUserControl.Size = new Size((int)((double)flowLayoutPanel1.Width * 0.9) , OurText.Font.Height);
OurUserControl.BackColor = OurColor;
OurUserControl.Controls.Add(OurText);
flowLayoutPanel1.Controls.Add(OurUserControl);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.