Search code examples
silverlightpositionmouseeventtransformitemscontrol

After placing ItemsControl item on canvas, get its Transform (Silverlight 5)


I position items from a collection on a canvas using an ItemsControl. The positioning is done by a TranslateTransform: <TranslateTransform X="{Binding x}" Y="{Binding y}"/>. To make the items clickable, I implemented the MouseLeftButtonUp event on the items.

See the complete code below:

<ItemsControl ItemsSource="{Binding XYPoints}">

    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Ellipse Width="20" Height="20" Fill="Red" MouseLeftButtonUp="XYPlotPoint_MouseLeftButtonUp">
                <Ellipse.RenderTransform>
                    <TransformGroup>
                        <RotateTransform Angle="0"/>
                        <TranslateTransform X="{Binding x}" Y="{Binding y}"/>
                    </TransformGroup>
                </Ellipse.RenderTransform>
                </Ellipse >
        </DataTemplate>
    </ItemsControl.ItemTemplate>

</ItemsControl>

What I cannot figure out is this: I want to be able to click on any of my items and get the TranslateTransform coordinates, i.e. the x and y values that were used to position the element on the canvas.

My idea was to get this from the sender of the event after casting the sender back to an Ellipse, e.g. Ellipse myEllipse = (Ellipse)sender; but I don't see any property that contains the information.

If I use GeneralTransform gt = myEllipse.TransformToVisual(Application.Current.RootVisual); it only gives me the Transform relative to the RootVisual, not to the grid I'm drawing on.

Perhaps I am overlooking something obvious here. I'd be grateful for any hint.


Solution

  • I found the solution. To get the transform of an UIElement (my item) that was clicked on relative to another UIElement (in my case the Grid it is placed on, which is also the LayoutRoot):

            private void XYPlotPoint_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            //cast sender to original type
            Ellipse myEllipse = (Ellipse)sender;
    
            //get the transform relative to the LayoutRoot
            GeneralTransform gt = myEllipse.TransformToVisual(LayoutRoot);
    
            //transform a new point to get the coordinates
            var myUiElementPosition = gt.Transform(new Point(0, 0));
        }