How do I bring an item to the front in wpf?

风流意气都作罢 提交于 2019-12-01 15:20:11
Ifeanyi Echeruo

You can use the Panel.ZIndex property to change the display order of elements in a panel

You have to use the Z index property, and because there are no built-in function to do what you want, I made my own. The higher the Z value, the 'closer' to front the control is. So you want to put your control on top without having to set an arbitrary high Z value.

So here is a small function I wrote for myself to do exactly that. Note: this assume that you are using a Canvas and UserControls. So you might need to adapt it a little bit if that's not your case.

Basically it will get the index of the control to move, then any control currently above it will go down by 1 and the control to move will be put on top (to maintain hierarchy).

    static public void BringToFront(Canvas pParent, UserControl pToMove)
    {
            try
            {
                int currentIndex = Canvas.GetZIndex(pToMove);
                int zIndex = 0;
                int maxZ = 0;
                UserControl child;
                for (int i = 0; i < pParent.Children.Count; i++)
                {
                    if (pParent.Children[i] is UserControl &&
                        pParent.Children[i] != pToMove)
                    {
                        child = pParent.Children[i] as UserControl;
                        zIndex = Canvas.GetZIndex(child);
                        maxZ = Math.Max(maxZ, zIndex);
                        if (zIndex > currentIndex)
                        {
                            Canvas.SetZIndex(child, zIndex - 1);
                        }
                    }
                }
                Canvas.SetZIndex(pToMove, maxZ);
            }
            catch (Exception ex)
            {
            }
    }

Instead of stacking the two grids, change the visibility properties so the grid you aren't using is collapsed.

To whom it may concern:

ZIndex property is 0 by default, so if you have (like me) a Canvas with more than 1 element (>4000 Shapes in my case), all will have ZIndex = 0, so changing the ZIndexes with this method will have no effect.

For this to work, I set the ZIndexes to a known value after creating all the elements, so they can be ordered after.

    int zIndex = 0; 
    for (int i = 0; i < canvas.Children.Count; i++) {
        UIElement child = canvas.Children[i] as UIElement;
        if (canvas.Children[i] is UIElement) Canvas.SetZIndex(child, zIndex++);
    }
SteveCav

A detailed example for this is Here

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!