开发者

.NET UserControl inherit parent form background

I have a WinFor开发者_运维百科ms control inherited from TreeView and I want it to automatically adjust background color according to the form (also customized) background. How to make it?


Making a control aware of its parent is normally a bad idea. There however is a dedicated method to detect the parent BackColor changing so it's okay. BackColor is an ambient property, if it isn't explicitly assigned then has the same value as the parent's BackColor. So take advantage of that:

using System;
using System.Windows.Forms;

class MyTreeView : TreeView {
    protected override void OnParentChanged(EventArgs e) {
        if (this.Parent != null) this.BackColor = this.Parent.BackColor;
        base.OnParentChanged(e);
    }
    protected override void OnParentBackColorChanged(EventArgs e) {
        this.BackColor = this.Parent.BackColor;
        base.OnParentBackColorChanged(e);
    }
}


If you were using some other control apart from the TreeView, the following advice would apply:

I haven't tried this on the TreeView control specifically, but the WinForms convention is that setting control.BackColor = Color.Transparent causes the parent background to show through.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜