asusralis
Topic Author
Posts: 142
Joined: 30 Jul 2018, 05:03

Trying to create a relative canvas

18 Jun 2019, 18:34

I wanted to create a canvas that has two attached properties that take a percentage of the canvas and put the element in that position. So, if a canvas is 400x400, and the XRatio and YRatio are 0.5, the element would be positioned at 200x200.
        protected override Size ArrangeOverride(Size arrangeSize)
        {
            foreach(FrameworkElement child in Children)
            {
                float xRatio = GetXRatio(child);
                float yRatio = GetYRatio(child);

                SetLeft(child, xRatio * arrangeSize.Width);
                SetTop(child, yRatio * arrangeSize.Height);
            }

            return arrangeSize;
        }
<ItemsControl Background="Transparent" BorderBrush="Transparent"
                     ItemsSource="{Binding X}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <local:RelativeCanvas/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemContainerStyle>
                    <Style TargetType="ContentPresenter">
                        <Setter Property="local:RelativeCanvas.XRatio" Value="{Binding Position.X}"/>
                        <Setter Property="local:RelativeCanvas.YRatio" Value="{Binding Position.Y}"/>
                    </Style>
                </ItemsControl.ItemContainerStyle>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <Button Width="50" Height="50"/>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
The ratios are correctly being set, and the ItemsControl has items, but none of the elements are visible. https://i.imgur.com/eADxTMb.png

EDIT: It seems the children's width/height are set, but their actual width/height is 0. What is making them not have a width or height?
 
User avatar
sfernandez
Site Admin
Posts: 2995
Joined: 22 Dec 2011, 19:20

Re: Trying to create a relative canvas

19 Jun 2019, 18:54

The ArrangeOverride method should call Arrange on the children to position them and generate their visual contents.
The code of your RelativeCanvas should look like this:
protected override Size ArrangeOverride(Size arrangeSize)
{
    foreach (UIElement child in Children)
    {
        float x = GetXRatio(child) * arrangeSize.Width;
        float y = GetYRatio(child) * arrangeSize.Height;

        child.Arrange(new Rect(new Point(x, y), child.DesiredSize))
    }

    return arrangeSize;
}
 
asusralis
Topic Author
Posts: 142
Joined: 30 Jul 2018, 05:03

Re: Trying to create a relative canvas

19 Jun 2019, 21:39

Ah, I see! Thank you very much.

Who is online

Users browsing this forum: Google [Bot], Semrush [Bot] and 26 guests