Resizing canvas items

前端 未结 3 1741
Happy的楠姐
Happy的楠姐 2021-01-24 15:07

I\'m trying to create canvas which resizes its children when canvas itself is resized. So I create my own class which inherits from canvas and overrides method ArrangeOverride w

3条回答
  •  孤独总比滥情好
    2021-01-24 15:40

    Ok, so I tried messing around with this and I found some hacky way to make it work. I don't really understand why it works this way (yet), but this works for me:

    public class CustomPanel : Canvas
    {
        private bool isFirstArrange = true;
    
        protected override Size ArrangeOverride(Size arrangeSize)
        {
            var ret = new Size();
            bool isFirstArrangeLocal = isFirstArrange;
            if (isFirstArrangeLocal)
            {
                ret = base.ArrangeOverride(arrangeSize);
                isFirstArrange = false;
            }
    
            var top = 0;
            foreach (UIElement child in Children)
            {
                Canvas.SetLeft(child, arrangeSize.Width - 20.0);
                child.SetValue(WidthProperty, arrangeSize.Width - Canvas.GetLeft(child));
                Canvas.SetTop(child, top);
                child.SetValue(HeightProperty, 20.0);
    
                top += 30;
            }
    
            if (!isFirstArrangeLocal)
            {
                ret = base.ArrangeOverride(arrangeSize);
            }
    
            return ret;
        }
    }
    

    So the idea is to put ArrangeOverride() after the foreach loop in all situations except on first call.

    The first call must be before foreach or for some reason I get this:

    Invalid

提交回复
热议问题