Same Z order for multiple controls in a C# Form application
I am worki开发者_运维问答ng on an application that has 3 different types of custom made controls - Planes, Connectors and Elements. User can add them on a canvas, move, delete them etc. So far all good. These 3 type of control MUST appear in a specific Z order no matter in which order user adds them on the canvas. That's where the problem is.
Planes MUST be at the bottom most position, elements MUST be at top most position and the connectors MUST be in-between Planes and the elements. This must be the case no matter how user add them on the canvas as well as when they are loaded from an XML file (which can be created by saving their positions and other properties etc.)
My question is - what is the best method to achieve the Z ordering that I want? Can multiple controls have same Z order (as mentioned above - all the planes must be on bottom most order and so on...)
Z-Order is determined by the index of the control in the parent control collection, so you would have to order the controls appropriately in the parent control collection to achieve the effect you want.
You can hook into the ControlAdded
event of the container to monitor when controls are added and perform the logic for the corresponding control type added to position it correctly.
You will likely have to keep track of the bounds for each control type for the index in the parent control and re-arrange when a control is added so that the planes remain as the lowest index and so on.
Form.Controls.SetChildIndex() is doing the trick for me. Even ControlAdded() could be used to set the child index. Thanks to "Quintin Robinson" for this suggestion.
Logic that I used for my purpose: I made 3 different (logical) groups of tab indices for all the user controls I have on the canvas. On Add/Delete control I quickly re-index all the controls that are on canvas. This way I always have current linear order of tab indices as they are assigned every time the number of controls on canvas changes.
Depending on my requirement of Z order for similar types of control, I re-index them. (e.g. all elements are indexed from 0 to i-1, connectors are indexed from i to j-1 and planes are indexed from j to k-1; where i, j, k are number of elements, connectors and planes respectively.)
精彩评论