.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.
精彩评论