簡體   English   中英

如何針對這些要求制作類似於自定義控件的網格

[英]How to make a Grid like custom control for these requirements

我需要具有以下功能的控件:

  1. 應該可以在xaml中使用它進行設計。
  2. 它應該能夠容納單個類型的多個子元素。 例如說Button
  3. 這些子元素將具有固定的尺寸。 控件必須弄清楚可以完全垂直和水平顯示的最大子級數量(不能部分顯示任何子級)。 並且僅顯示那些孩子,但保留不可見的孩子供以后使用。 -我認為我可以通過Grid完成此要求。
  4. 應該可以為這些子元素設置動畫-我想這不是問題。

我試圖編寫一個自定義控件來執行此操作。 我從Grid繼承而來,看到Grid實現了IAddChild我認為如果我覆蓋AddChild就可以捕獲正在添加的元素。 但是現在我發現Grid也沒有針對AddChild實現! 所以看來我不能那樣做。 我應該從哪里開始?

編輯:由於艾倫的指針,我得到了它的工作...

public class AutoLayoutingPanel : Panel
{
    protected override Size MeasureOverride(Size availableSize)
    {
        Size size = new Size();
        size.Height = double.MaxValue;
        size.Width = double.MaxValue;

        foreach (UIElement child in Children)
        {
            child.Measure(size);
            size.Height += child.DesiredSize.Height;
            size.Width += child.DesiredSize.Width;
        }

        return availableSize;
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        ArrangeGrid(finalSize);
        return finalSize;
    }

    private void ArrangeGrid(Size finalSize)
    {
        foreach (UIElement child in Children)
        {
            child.Visibility = Visibility.Hidden;
        }

        Size maxCellSize = new Size();

        foreach (UIElement child in Children)
        {
            maxCellSize.Height = Math.Max(child.DesiredSize.Height, maxCellSize.Height);
            maxCellSize.Width = Math.Max(child.DesiredSize.Width, maxCellSize.Width);
        }

        int rowCount = (int)Math.Floor(finalSize.Height / maxCellSize.Height);
        int colCount = (int)Math.Floor(finalSize.Width / maxCellSize.Width);

        int row = 0, col = 0;
        foreach (UIElement child in Children)
        {
            if (row < rowCount && col < colCount)
            {
                Rect pos = new Rect(col * maxCellSize.Width, row * maxCellSize.Height, maxCellSize.Width, maxCellSize.Height);
                child.Visibility = System.Windows.Visibility.Visible;
                child.Arrange(pos);
            }
            else
            {
                break;
            }

            if (++row >= rowCount)
            {
                row = 0;
                ++col;
            }
        }
    }
}

我認為您需要創建一個自定義布局面板,而不是嘗試從Grid繼承(就IAddChild接口而言,它是使用EIMI實現的,因此從外部看不到或無法覆蓋)。 是一個很好的起點。

(此外,您還需要考慮如何限制控件可以容納的子控件的類型。可以選擇使用泛型,但我對XAML泛型支持感到懷疑。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM