WPF 容器的Z顺序操作

      当需要动态添加、修改、删除控件时,如果要达到最好的效果,肯定不只是把需要的控件添加到容器中,并且还需要把容器中的已有控件进行排序操作(置顶、置底、前移、后移操作)。由于初次接触到wpf,所以对很多知识都不熟悉,现自己动手实现了一个Zindex的操作算法。

      /// <summary>
        /// 操作控件的Z顺序
        /// </summary>
        /// <param name="sender">菜单</param>
        /// <param name="moveToFront">True 前移 ,false 置后</param>
        /// <param name="toBottom">true 移动至底端,false 移动一层</param>
        private void doMoveZindex(object sender, bool moveToFront, bool toBottom)
        {
            UIElement ui = ContextMenuService.GetPlacementTarget(LogicalTreeHelper.GetParent(sender as MenuItem));
            if (ui is FrameworkElement)
            {
                FrameworkElement fui = ui as FrameworkElement;
                if (fui == null) return;

                int nowZIndex = Canvas.GetZIndex(fui);


                //deviceOperator.DeviceCollection保存的就是每个控件对应设备的位置和z顺序值
//取得最大z顺序
int maxZindex = deviceOperator.DeviceCollection .Select(t => t.ZIndex1) .Max(); //需要转换的zindex int nextZindex = -1; if (moveToFront) //前移 { //如果已经位于最顶层,则取消 if (nowZIndex == maxZindex) return; if (toBottom) //移动到最顶层 { nextZindex = maxZindex; foreach (FrameworkElement childElement in parentCanvas.Children) { int zi = Canvas.GetZIndex(childElement); if (zi > nowZIndex) { Canvas.SetZIndex(childElement, zi - 1); updateDevice(childElement); maxZindex = -1; } } } else//上移一层 { nextZindex = nowZIndex + 1; foreach (FrameworkElement childElement in parentCanvas.Children) { if (Canvas.GetZIndex(childElement) == nextZindex) { Canvas.SetZIndex(childElement, nowZIndex); updateDevice(childElement); maxZindex = -1; break; } } } if (maxZindex == -1) { Canvas.SetZIndex(fui, nextZindex); updateDevice(fui); } } else //置底 { if (nowZIndex == 0) return; if (toBottom) { nextZindex = 0; foreach (FrameworkElement childElement in parentCanvas.Children) { int zi = Canvas.GetZIndex(childElement); if (zi < nowZIndex) { Canvas.SetZIndex(childElement, zi + 1); updateDevice(childElement);//保存控件的Z顺序值到deviceoperator.DeviceCollection maxZindex = -1; } } } else { nextZindex = nowZIndex - 1; foreach (FrameworkElement childElement in parentCanvas.Children) { if (Canvas.GetZIndex(childElement) == nextZindex) { Canvas.SetZIndex(childElement, nowZIndex); updateDevice(childElement); maxZindex = -1; break; } } } if (maxZindex == -1) { Canvas.SetZIndex(fui, nextZindex); updateDevice(fui); } } } }

 

//调用方法
//前移
 doMoveZindex(sender, true, false);
//置项
  doMoveZindex(sender, true, true);
//后移
 doMoveZindex(sender, false, false);
//置底
 doMoveZindex(sender, false, true);

这样的一个前提条件是容器中的每一个控件的ZIndex值都不会相同。

待解决的问题:现在变化的z顺序,是针对整个容器来说的。如果可以针对控件的重叠区域,进行修改Z顺序,那么速度应该会得到相应的提升。

转载于:https://www.cnblogs.com/ouxianzhi520/p/3173493.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值