I have the following code
public partial class MainWindow : Window
{
public MainWindow() {
InitializeComponent();
}
List<UIElement> ucs = new List<UIElement>();
private void Window_PreviewMouseLeftButtonDown(object sender,
MouseButtonEventArgs e)
{
ucs.Clear();
Point p = e.GetPosition((UIElement)sender);
VisualTreeHelper.HitTest(this, null,
new HitTestResultCallback(MyHitTestCallback),
new PointHitTestParameters(p));
Console.WriteLine("ucs.Count = {0}", ucs.Count);
foreach (var item in ucs)
{
Console.WriteLine("item: {0}", item.ToString());
}
}
HitTestResultBehavior MyHitTestCallback(HitTestResult result)
{
ucs.Add(result.VisualHit as UIElement);
return HitTestResultBehavior.Continue;
}
}
this is my window
<Window>
<Grid>
<my:UserControl1 HorizontalAlignment="Left" Margin="82,88,0,0" x:Name="userControl11" VerticalAlignment="Top" />
<my:UserControl1 HorizontalAlignment="Left" Margin="168,166,0,0" x:Name="userControl12" VerticalAlignment="Top" />
<my:UserControl1 HorizontalAlignment="Left" Margin="231,130,0,0" x:Name="userControl13" VerticalAlignment="Top" />
</Grid>
</Window>
this is my UC
<UserControl>
<Grid>
<Label Content="Label" Height="44" HorizontalAlignment="Left" Name="label1" VerticalAlignment="Top" FontSize="20" FontWeight="Bold" Width="78" Background="#FF4B9FC4" BorderBrush="#FF020A0D" BorderThickness="1" />
</Grid>
</UserControl>
this is the output when I click ON A USER CONTROL, then on a intersection of 2 UserControls:
ucs.Count = 2
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border
ucs.Count = 3
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border
Why this? Where is the UserControl under the mouse instance?
PS:
Now, when I have on the Label the BorderThickness = 0
ucs.Count = 3
item: System.Windows.Controls.TextBlock
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border
ucs.Count = 3
item: System.Windows.Controls.TextBlock
item: System.Windows.Controls.Border
item: System.Windows.Controls.Border