count controls of type A under the mouse in WPF
我在画布上有一些自定义的 A 面板,那里也有 B 面板,我如何计算 A 面板实际上位于鼠标光标处?
我知道这可以通过
这是我的代码
1
2 3 4 5 6 7 8 9 10 11 12 13 14 |
<UserControl x:Class="WpfApplication7.UserControl1"> <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> <Window x:Class="WpfApplication7.MainWindow" |
.cs
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } List<UserControl1> ucs = new List<UserControl1>(); private void Window_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) private void GetUcsCount(MouseButtonEventArgs e) Point p = e.GetPosition(this); VisualTreeHelper.HitTest(this, null, HitTestResultBehavior MyHitTestCallback(HitTestResult result) return HitTestResultBehavior.Continue; |
对于 HitTestResultCallback 中的每个命中,您可以尝试查找父 UserControl1 并将其添加到列表中(如果尚未添加)
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
HitTestResultBehavior MyHitTestCallback(HitTestResult result)
{ DependencyObject visualHit = result.VisualHit; UserControl1 parentUserControl = GetVisualParent<UserControl1>(visualHit); if (parentUserControl != null && ucs.IndexOf(parentUserControl) < 0) { ucs.Add(parentUserControl as UserControl1); } return HitTestResultBehavior.Continue; } public static T GetVisualParent< T >(object childObject) where T : Visual { DependencyObject child = childObject as DependencyObject; while ((child != null) && !(child is T)) { child = VisualTreeHelper.GetParent(child); } return child as T; } |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/269807.html