修改自定义WrapPanel以添加换行功能

时间:2017-12-01 15:56:55

标签: c# .net wpf wrappanel

我尝试修改找到here的解决方案,以便有一个单独的方法来插入换行符。

到目前为止,我能够做到的是非常hackish但是我基本上插入了一个我不会在WrapPanel中使用的控件类型,从那里我玩了所需的大小值来欺骗小组认为它是时候把内容包装好了。

protected override Size MeasureOverride(Size constraint)
{
    Size curLineSize = new Size();
    Size panelSize = new Size();

    UIElementCollection children = base.InternalChildren;

    for (int i = 0; i < children.Count; i++)
    {
        UIElement child = children[i] as UIElement;

        // Flow passes its own constraint to children
        child.Measure(constraint);
        Size sz = child.DesiredSize;

        if (child.GetType() == typeof(TextBlock))
        {
            sz.Width = constraint.Width + 1;
        }

        if (curLineSize.Width + sz.Width > constraint.Width) //need to switch to another line
        {
            panelSize.Width = Math.Max(curLineSize.Width, panelSize.Width);
            panelSize.Height += curLineSize.Height;
            curLineSize = child.DesiredSize;

            if (sz.Width > constraint.Width) // if the element is wider then the constraint - give it a separate line                    
            {
                sz = child.DesiredSize;
                panelSize.Width = Math.Max(sz.Width, panelSize.Width);
                panelSize.Height += sz.Height;
                curLineSize = new Size();
            }
        }
        else //continue to accumulate a line
        {
            curLineSize.Width += sz.Width;
            curLineSize.Height = Math.Max(sz.Height, curLineSize.Height);
        }
    }

    // the last line size, if any need to be added
    panelSize.Width = Math.Max(curLineSize.Width, panelSize.Width);
    panelSize.Height += curLineSize.Height;

    return panelSize;
}

重要的行是if (child.GetType() == typeof(TextBLock))sz.Width = constraint.Width + 1;从那里我将curLineSize = child.DesiredSize;更改为&#39; curLineSize = child.DesiredSize to keep in consistent with original code. Finally, I also set sz = child.DesiredSize;`保持这部分一致。

我知道这非常hackish,这就是为什么我一直试图创建某种可以调用的方法,只是插入一个换行符,但我没有运气。

0 个答案:

没有答案