Why doesn't toolstriplabel's backcolor property change during design time or run time?
Asked Answered
E

3

4

I need to have a toolstrip label and its back color changed during runtime, but no matter what I do. It just won't change its backcolor, even though they give option to change its backcolor. Why is that and how do you get its backcolor property to change during runtime or design time?

Thanks in advance,

Elegancy answered 7/11, 2011 at 13:55 Comment(0)
A
9

This is affected by the ToolStrip's RenderMode setting. Only when you change it to System will the BackColor property have an effect. The other renderers use theme colors. You are probably not going to like System very much, but you can have you cake and eat it too by implementing your own renderer. Make it look similar to this:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.toolStrip1.Renderer = new MyRenderer();
    }
    private class MyRenderer : ToolStripProfessionalRenderer {
        protected override void OnRenderLabelBackground(ToolStripItemRenderEventArgs e) {
            using (var brush = new SolidBrush(e.Item.BackColor)) {
                e.Graphics.FillRectangle(brush, new Rectangle(Point.Empty, e.Item.Size));
            }
        }
    }
}
Autosome answered 7/11, 2011 at 14:30 Comment(0)
S
3

I did not like changing the RenderMode so I went with this:

private static void SetBackgroundColor(ToolStripLabel tsl, Color c)
    {
        if (tsl != null)
        {
            Bitmap bm = new Bitmap(1, 1);
            using (Graphics g = Graphics.FromImage(bm)) { g.FillRectangle(new SolidBrush(c), 0, 0, 1, 1); }
            tsl.BackgroundImageLayout = ImageLayout.Stretch;
            Image oldImage = tsl.BackgroundImage;
            tsl.BackgroundImage = (Image)bm.Clone();
            if (oldImage != null) { oldImage.Dispose(); }
            bm.Dispose();
        }
    }

Uses BackgroundImage to fill in solid color bitmaps.

You could probably attach to the BackColorChanged event and call this function.

Sarracenia answered 4/8, 2021 at 20:6 Comment(0)
L
3

Good idea, @Plater. Thanks. I tried to make your code even simpler and it works for me :-)

ToolStripLabel.BackgroundImageLayout = ImageLayout.Stretch
ToolStripLabel.BackgroundImage = New Bitmap(1, 1)
Dim g As Graphics = Graphics.FromImage(ToolStripLabel.BackgroundImage)
g.Clear(Color.PaleGreen)
Lite answered 8/2, 2022 at 19:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.