WPF(1) 自定义面板-阶梯状面板

2021-07-16 09:20

阅读:559

wpf中提供了几个内置的布局,如StackPanel,Grid,DockPanel,Canvas等,其实也可以继承自Panel并重写MeasureOverride和ArrangeOverride方法自定义一个面板中的元素布局格式,例子:

技术分享图片

 

窗口缩小后:

技术分享图片

 

图中最外面是一个自定义面板StairPanel,  其中1,2,3处分别为三个子元素,2为按钮,1和3又是StairPanel, 其中分别又有四个按钮,仍然是阶梯状布局。

当窗口大小改变后是自适应的。

xaml:

  
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1._24"
        mc:Ignorable="d"
        Title="Window1" Height="800" Width="800">
   
       
           
               
                   
                       
                       
                   
               
           
       
       
           
               
                   
                       
                       
                   
               
           
       
       
           
               
                   
                       
                       
                   
               
           
       
   
   
       
           
           
           
           
       
       
       
           
           
           
           
       

   

cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1._24
{
    public class StairPanel : Panel
    {
        // Default public constructor
        public StairPanel()
            : base()
        {
        }

        // Override the default Measure method of Panel
        protected override Size MeasureOverride(Size availableSize)
        {
            Size panelDesiredSize = new Size();

            foreach (UIElement child in InternalChildren)
            {
                child.Measure(availableSize);
                panelDesiredSize = child.DesiredSize;
            }

            return panelDesiredSize;
        }
        protected override Size ArrangeOverride(Size finalSize)
        {
            //根据面板的大小和子元素个数等分宽度和高度
            double stepWidth = finalSize.Width / InternalChildren.Count;
            double stepHeight = finalSize.Height / InternalChildren.Count;


            double x = 0;
            double y = 0;

            foreach (UIElement child in InternalChildren)
            {
                child.Arrange(new Rect(new Point(x, y), new Size(stepWidth, stepHeight)));

     //递增子元素位置
                x += stepWidth;
                y += stepHeight;
            }
            return finalSize;
        }
    }
}

  

 

上一篇:WPF-控件(1)

下一篇:SignalR-WinForm服务端


评论


亲,登录后才可以留言!