c# winforms toolstripmenuitem change background

2019-05-31 22:31发布

OK, someone please tell me why this is not working.

I have a simple MenuStrip in winforms app (c#). It has ToolStripMenuItems.

In the properties window of the designer, I select BackColor = White. In Desginer.cs file I can see it.

Running the app, the background color is Control (grey).

What is going? Why is the backcolor not white?

Thanks

EDIT

This is the code from the Designer.cs:

   this.menuRefresh.BackColor = System.Drawing.Color.White;

Refresh item should be white

EDIT2:

In the code, after loading the form (in the constructor and also in Form_Load event I've placed this:

 menuRefresh.BackColor = Color.White;

Also not helping.

2条回答
ゆ 、 Hurt°
2楼-- · 2019-05-31 22:48

The BackColor of the MenuStrip does not determine the background colour of the items included in any tool strip menus (drop downs). These items each have their own BackColor property, which must be set separately.

For example, your "Refresh" item is it's own ToolStripMenuItem, so you need to set the BackColor of that to White also.


In regards to your second edit, setting menuRefresh.BackColor = Color.White; should work fine in either the constructor, or the Form_Load event. I have tested it with both and it works as expected.

查看更多
家丑人穷心不美
3楼-- · 2019-05-31 22:57

You need to implement a simple renderer class to achieve this. Here is an example:

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
      InitializeComponent(); 
      menuStrip1.Renderer = new MyRenderer(); 
    } 

    private class MyRenderer : ToolStripProfessionalRenderer 
    { 
        protected override void OnRenderMenuItemBackground(ToolStripItemRenderEventArgs e)      
        { 
            Rectangle rc = new Rectangle(Point.Empty, e.Item.Size); 
            Color c = e.Item.Selected ? Color.Azure : Color.Beige; 
            using (SolidBrush brush = new SolidBrush(c)) 
                e.Graphics.FillRectangle(brush, rc); 
        } 
    } 
} 
查看更多
登录 后发表回答