Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
.net 使用新元素进行命中测试_.net_Wpf_Hittest_Uielement - Fatal编程技术网

.net 使用新元素进行命中测试

.net 使用新元素进行命中测试,.net,wpf,hittest,uielement,.net,Wpf,Hittest,Uielement,我正在创建一个WPF usercontrol,它需要检查新的UIElements是否与任何现有的UIElements重叠。在调用button1\u Click之前将baseRectangle添加到画布时,下面的代码可以正常工作,但如果在button1\u Click方法中添加了矩形,则hittest不起作用 <Window x:Class="WpfCollisionTest.MainWindow" xmlns="http://schemas.microsoft.com/wi

我正在创建一个WPF usercontrol,它需要检查新的UIElements是否与任何现有的UIElements重叠。在调用button1\u Click之前将baseRectangle添加到画布时,下面的代码可以正常工作,但如果在button1\u 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");
     }
 }

公共主窗口()
{ 
初始化组件();
}
私有无效按钮1\u单击(对象发送者,路由目标)
{
canvas1.Children.Clear();
矩形rect=新矩形();
矩形宽度=200;
直线高度=200;
rect.Fill=刷子。红色;
canvas1.Children.Add(rect);
if(VisualTreeHelper.HitTest(canvas1,新点(100100))!=null)
{
MessageBox.Show(“冲突”);
}
}

将rect添加到画布后,尝试添加以下内容:

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

当然,每次更新rect的布局时,都会遇到这个问题。。。因此,您可能希望删除该处理程序,或在其内部执行进一步检查。

在hittest解决问题之前调用canvas1.UpdateLayout()。

必须先呈现控件,然后才能点击test。可能以低于
Render
的调度程序优先级运行命中测试这种方法的问题是,我需要添加几十个需要命中测试的对象。有没有办法在渲染之前“手动”进行HIT测试?如果有帮助的话,我需要对我在一个单独集合中拥有的一堆文本块进行hittests就在命中测试代码之前。这只是猜测,谢谢你,克莱门斯。你的解决方案奏效了。