I've recently come across the following situation. I have a UserControl
that can show a modeless toolbox. If the user has shown the toolbox, I'd like to hide and show it appropriately as the UserControl
itself becomes invisible or visible, respectively. The UserControl
can be embedded in an arbitrary number of parent containers, such as a GroupBox
or TabPage
, which can influence whether or not the UserControl
is actually visible despite its own Visible
property being True
.
In WPF, it seems like I could use the IsVisibleChanged
event of the UserControl
to handle this. Is there an equivalent for WinForms? What would a general solution in .NET 2.0 be?
EDIT: Here is the solution that I arrived at. Is there a better solution?
public partial class MyControl : UserControl
{
private List<Control> _ancestors = new List<Control>();
private bool _isVisible = false;
public MyControl()
{
InitializeComponent();
ParentChanged += OnParentChanged;
VisibleChanged += OnVisibleChanged;
}
private void OnParentChanged(object sender, EventArgs e)
{
foreach (Control c in _ancestors)
{
c.ParentChanged -= OnParentChanged;
c.VisibleChanged -= OnVisibleChanged;
}
_ancestors.Clear();
for (Control ancestor = Parent; ancestor != null; ancestor = ancestor.Parent)
{
ancestor.ParentChanged += OnParentChanged;
ancestor.VisibleChanged += OnVisibleChanged;
_ancestors.Add(ancestor);
}
}
private void OnVisibleChanged(object sender, EventArgs e)
{
bool isVisible = Visible;
foreach (Control c in _ancestors)
{
if (!c.Visible)
{
isVisible = false;
break;
}
}
if (isVisible != _isVisible)
{
_isVisible = isVisible;
// Control visibility has changed here
// Do something
}
}
}