views:

281

answers:

1

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
        }
    }
}
A: 

Unfortunately, when working with multiple forms or controls, properties like Visible require that you set them manually. It's a pain, and somewhat tedious to go through all controls whose properties are dependent on other controls' properties.

What if you set the UserControl.Tag to reference your toolbox?

dboarman
I'm accepting this because there seems to be no alternative to checking the visibility myself. I did not use Tag.
Eric