使用新的UIElements进行测试

时间:2012-01-30 14:21:59

标签: .net wpf hittest uielement

我正在创建一个WPF-usercontrol,需要检查新的UIElements是否与任何现有的UIElements不重叠。在调用button1_Click之前将baseRectangle添加到画布时,下面的代码工作正常,但如果在button1_Click方法中添加了矩形,则hittest不起作用。

<Window x:Class="WpfCollisionTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Canvas Height="246" HorizontalAlignment="Left" Margin="12,12,0,0" Name="canvas1" VerticalAlignment="Top" Width="479"></Canvas>
        <Button Content="Button" Height="35" HorizontalAlignment="Left" Margin="12,264,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    </Grid>
</Window>


 public MainWindow()
 { 
     InitializeComponent();
 }

 private void button1_Click(object sender, RoutedEventArgs e)
 {
     canvas1.Children.Clear();
     Rectangle rect = new Rectangle();
     rect.Width = 200;
     rect.Height = 200;
     rect.Fill = Brushes.Red;
     canvas1.Children.Add(rect);
     if (VisualTreeHelper.HitTest(canvas1, new Point(100, 100)) != null)
     {
         MessageBox.Show("Collision");
     }
 }

2 个答案:

答案 0 :(得分:1)

在最热门之前调用canvas 1.UpdateLayout()解决问题。

答案 1 :(得分:0)

尝试将rect添加到画布后添加:

canvas1.Children.Add(rect);
rect.LayoutUpdated += (s, args) =>
{
    if (VisualTreeHelper.HitTest(canvas1, new Point(100, 100)) != null)
    {
        MessageBox.Show("Collision");
    }
};

当然,每次更新rect的布局时都会出现这种情况......所以你可能想要删除处理程序,或者在其中进一步检查。