BringToFront in WPF

后端 未结 5 1037
小鲜肉
小鲜肉 2020-12-17 14:54

I need to bring to front a custom control in WPF.

pseudoCode

OnMouseDown()
{
    if (this.parent != null)
        this.parent.BringToFront(this);
}
<         


        
5条回答
  •  太阳男子
    2020-12-17 15:07

    Here is an extension function that adds the method BringToFront functionality to all FrameworkElements that are contained in a Panel.

      public static class FrameworkElementExt
      {
        public static void BringToFront(this FrameworkElement element)
        {
          if (element == null) return;
    
          Panel parent = element.Parent as Panel;
          if (parent == null) return;
    
          var maxZ = parent.Children.OfType()
            .Where(x => x != element)
            .Select(x => Panel.GetZIndex(x))
            .Max();
          Panel.SetZIndex(element, maxZ + 1);
        }
      }
    

提交回复
热议问题