I am trying to do hit testing on a collection of user controls added to a canvas at runtime.
My canvas:
<Canvas x:Name="LayoutRoot" Background="White">
<Canvas x:Name="Carrier" Canvas.ZIndex="-1">
</Canvas>
</Canvas>
My canvas code:
public MainPage()
{
InitializeComponent();
var uiElement = new MyUserControl();
this.Carrier.Children.Add(uiElement);
MouseLeftButtonDown += MouseLeftButtonDownHandler;
}
private List<UIElement> HitSprite(Point p)
{
var hitElements =
VisualTreeHelper.FindElementsInHostCoordinates(p, this.Carrier) as List<UIElement>;
return hitElements.Count > 0 ? hitElements : null;
}
private void MouseLeftButtonDownHandler(object sender, MouseButtonEventArgs e)
{
var list = HitSprite(e.GetPosition(this.LayoutRoot));
}
My user control:
<Canvas x:Name="Container" AllowDrop="True">
<StackPanel Name="Description" Height="65" Canvas.ZIndex="2" IsHitTestVisible="False">
<TextBlock Text="Testing" x:Name="Name" FontSize="12" FontWeight="Bold" HorizontalAlignment="Center" IsHitTestVisible="False"/>
<Border Background="Green">
<Image x:Name="Body" Stretch="None" Canvas.ZIndex="0" Height="20" Width="20">
</Image>
</Border>
</StackPanel>
</Canvas>
I've tried various combinations of Carrier and LayoutRoot for GetPoint and FindElementsInHostCoordinates but the elements returned are always empty.
What am I doing wrong?