Main control to close child

2019-08-08 21:02发布

问题:

I have one MainControl that contains a ChildControl. The ChildControl has a hide button that would hide itself. When hidden I expect the MainControl to hook the event and dispose it.

  • MainControl
    • ChildControl > Hide button

Can't figure out how I should hook those.

Any tip? Thank you!

回答1:

You can create an event that will notify the main control that the child control is hidden, and in your main control, handling the event, you can dispose of your control.

Below is a small sample code of how you can go about creating your event for the hidden action.

    class MainControl
    {
        ChildControl childControl;

        public MainControl()
        {
            childControl = new ChildControl();
            childControl.VisibilityChanged += childControl_VisibilityChanged;
        }

        void childControl_VisibilityChanged(object sender, HiddenEvent e)
        {
            if (e.isHidden)
            {
                //close control here
            }
        }
    }

    public class HiddenEvent : EventArgs
    {
        public HiddenEvent(bool propertyValue)
        {
            this.isHidden = propertyValue;
        }

        public bool isHidden { get; set; }
    }
    public class ChildControl
    {
        public event EventHandler<HiddenEvent> VisibilityChanged;

        public ChildControl()
        {

        }

        private bool _isHidden;
        public bool Control
        {
            get
            {
                return _isHidden;
            }
            set
            {
                _isHidden = value;
                Hidden_Handler(value);
            }
        }

        private void Hidden_Handler(bool isHidden)
        {
            var handler = VisibilityChanged;
            if (handler != null)
                VisibilityChanged(this, new HiddenEvent(isHidden));
        }
    }


回答2:

As an option you could bind ChildControl's button to a remove command on the main control (using RelativeSource) and let MainControl do all the work