c# winforms toolstripmenuitem change background

若如初见. 提交于 2019-12-23 01:26:49

问题


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;

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.


回答1:


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); 
        } 
    } 
} 



回答2:


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.



来源:https://stackoverflow.com/questions/25425948/c-sharp-winforms-toolstripmenuitem-change-background

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!