How to update the layout whenever a control changes height in Winforms?
I have a custom LayoutEngine and it handles the layout correctly. However I want the layout to update (be called again) if any control changes height.
Is this possible? If so how and where should I do this? Inside the control, or the layout e开发者_JS百科ngine? Preferably I wouldn't want this code to be duplicated wherever I have this layout used.
So if I can encapsulate it inside the control or the layoutengine that would be good.
In the control or layout container :
- define a
Dictionary<Control,int>
which will hold a current height variable for each Control of interest.
In the initial Layout :
recurse through Controls of interest (if nested), or
iterate through Controls of interest (if not nested)
... use "standard" iteration or recursion, Linq recursion, or Linq "iteration" ... :
... as you recurse, or iterate, make an entry in the Dictionary for each Control with its current height ...
... attach a 'SizeChanged handler to each Control of interest that invokes the same method in your Layout Engine Class (possibly a static method ?) : for the sake of clarity : let's refer to that as the "Event Dispatch Code."
In your Event Dispatch Code for all Controls of interest, now triggered by a SizeChanged event on any of your "monitored" Controls :
do a dictionary look-up using the Control as a key : get the Height property value and compare with the Control's current Height value :
assuming the Height property has changed :
a. call your Layout Engine to "do its thing."
b. update Dictinary value for Height for that Control.
Note : since the SizeChanged event is going to be called with 'sender as an 'object : you will need to cast it to type Control before accessing its 'Height property.
Here's a "rough sketch" of what your code might look like :
// note : untested code : use caution ... test rigorously ...
// stub for the Dictionary of monitored Controls
private Dictionary<Control, int> LayoutManager_MonitoredControls = new Dictionary<Control, int>();
// the SizeChanged Event Handler you "install" for all Controls you wish to monitor
private void LayoutManager_SizeChanged(object sender, EventArgs e)
{
Control theControl = sender as Control;
int cHeight = theControl.Height;
if (LayoutManager_MonitoredControls[theControl] != theControl.Height);
{
// update the Dictionary
LayoutManager_MonitoredControls[theControl] = cHeight;
// call your code to update the Layout here ...
}
}
精彩评论