I have a SplitContainer I want to catch the Panel2 collapsing and expanding events.
Any idea how to do that?
Posting this for others that might be hunting for the same answer as I was.
Unfortunately SplitContainer doesn't offer any direct events for the collapsed events. What I have found useful is to monitor the SizeChanged and/or ClientSizeChanged events of the OPPOSITE panel to the one you're collapsing.
Meaning, if I am interested in monitoring collapses of Panel2, I would subscribe to ClientSizeChanged events for Panel1.
In practice I would recommend monitoring the ClientSizeChanged for both panels of the SplitContainer to guarantee you don't miss any initialization or direct splitter movements.
In the below example I have a toggle button (btnToggle) that I want the Checked state to follow the visibility of Panel2 in the SplitContainer:
private void splitContainer_Panel2_ClientSizeChanged(object sender, EventArgs e)
{
btnToggle.Checked = !splitContainer.Panel2Collapsed;
}
private void splitContainer_Panel1_ClientSizeChanged(object sender, EventArgs e)
{
btnToggle.Checked = !splitContainer.Panel2Collapsed;
}
splitContainer.Panel1.VisibleChanged += (s, e) => { bool isPanel1Collapsed = splitContainer.Panel1Collapsed; };
In the internal implementation, when a panel in a SplitContainer
is collapsed, is Visible
property is set to false
and vice-versa. It is therefore possible to detect the changes when a panel is collapsed by handling the VisibleChanged
event of the desired panel.
The catch is that the SplitterPanel
class doesn't expose this event. However, since it inherits the Panel
class which exposes this event, you can cast to a Panel
and handle the event from there as demonstrated in the sample code below.
private void Initialize()
{
split = new SplitContainer();
((Panel)split.Panel1).VisibleChanged += splitPanel1_Collapsed;
}
private void splitPanel1_Collapsed(object sender, EventArgs e)
{
var panel = (SplitterPanel)sender;
var panelCollapsed = !panel.Visible;
}
There isn't an event exactly for that, but that's because you should know when it's getting collapsed when the code it run:
splitContainer1.Panel1Collapsed = true;
// do your stuff
Otherwise, you can watch for the SplitterMoved
or SplitterMoving
events on the SplitContainer control.