WPF: Capture Click Coordinates of an Image in an ItemsControl

It can be tricky to get the click coordinates of a control inside an ItemsControl. Here is how you do it:

XAML:

<ItemsControl Name="FileImages">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal" />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Image Name="FileImage" Source="{Binding}" Focusable="True" MouseUp="FileImage_OnMouseUp" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Code Behind:

private void FileImage_OnMouseUp(object sender, MouseButtonEventArgs e)
{
    var frameworkElement = (FrameworkElement)sender;
    var fileImage = (IInputElement)frameworkElement.FindName("FileImage");

    var point = e.GetPosition(fileImage);

    MessageBox.Show(
        string.Format("X: {0}; Y: {1}", point.X, point.Y),
        "Coordinates");
}
Tagged on: ,

Leave a Reply

Your email address will not be published. Required fields are marked *