How to bind absolute coordinates of a shape/control inside Canvas
Asked Answered
I

1

2

On a Windows 8.1 Metro app, I'm trying bind a collection of shapes from my view model into MainPage.xaml. Each shape will have a Left, Top and also a PathData which will be a RectangleGeometry that contains the rectangle that I want drawn inside the canvas at the corresponding position.

This is the XAML :

<Grid Background="Black">
    <ItemsControl ItemsSource="{Binding Shapes}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemContainerStyle>
            <Style TargetType="ContentPresenter">
                <Setter Property="Canvas.Top" Value="{Binding Top}"/>
                <Setter Property="Canvas.Left" Value="{Binding Left}"/>
            </Style>
        </ItemsControl.ItemContainerStyle>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Path Data="{Binding PathData}" Stroke="White" StrokeThickness="3" Canvas.Left="{Binding Left}" Canvas.Top="{Binding Top}"/>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
</Grid>

The data context is set and working correctly. I populate the Shapes from MainViewModel and the rectangles do appear on the screen, but the problem is I can't get the rectangles to be placed at the exact Left and Top locations inside the Canvas, i.e. they are just placed at (0,0).

I tried both binding the Path's Canvas.Left and Canvas.Top (the obvious method I tried) as well as setting an ItemContainerStyle with a Style (a method I found from a WPF example) that is supposed to do the same. But neither of these work (I've added both methods in the xaml for reference).

So what am I doing wrong and how do I make the rectangles appear at the corresponding positions ?


Edit : My question is the same as this one for WPF except that I'm targeting windows metro/uwp for which that accepted answer doesn't work.

Icao answered 14/6, 2016 at 18:36 Comment(0)
I
4

Got around the problem by binding into a Transform instead.

<Path Data="{Binding PathData}" Stroke="White" StrokeThickness="3">
    <Path.RenderTransform>
         <CompositeTransform TranslateX="{Binding Left}" TranslateY="{Binding Top}"/>
    </Path.RenderTransform>
</Path>
Icao answered 14/6, 2016 at 20:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.