开发者

How to update the layout whenever a control changes height in Winforms?

开发者 https://www.devze.com 2022-12-16 22:24 出处:网络
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.

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 :

  1. define a Dictionary<Control,int> which will hold a current height variable for each Control of interest.

In the initial Layout :

  1. recurse through Controls of interest (if nested), or

  2. 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 :

  1. 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 :

  2. 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 ...
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号