Skip to main content
 首页 » 编程设计

c#之Bounds.Intersect for WPF

2024年02月23日17lvdongjie

我有一个 Winforms 应用程序,允许用户在屏幕上拖放一些标签。

目标是将匹配的标签放在彼此之上。

我在列表中保留对这些标签的引用,目前我正在通过执行以下操作检查它们是否重叠。

    foreach (List<Label> labels in LabelsList) 
        { 
            var border = labels[1].Bounds; 
            border.Offset(pnl_content.Location); 
 
            if (border.IntersectsWith(labels[0].Bounds)) 
            { 
                labels[1].ForeColor = Color.Green; 
            } 
            else 
            { 
                labels[1].ForeColor = Color.Red; 
            } 
        } 

问题在于这仅适用于 Winforms (Bounds.Intersect)。我可以在 WPF 中做什么来获得相同的结果?

如果有所不同,我目前正在将两个标签添加到不同的 <ItemsControl>在我看来。

请您参考如下方法:

所以感谢评论,我能够做我需要的。

对于所有在家玩的人来说,WPF 代码现在看起来像这样:

    public void Compare() 
    { 
 
        foreach (List<Label> labels in LabelsList) 
        { 
            Rect position1 = new Rect(); 
            position1.Location = labels[1].PointToScreen(new Point(0, 0));                 
            position1.Height = labels[1].ActualHeight; 
            position1.Width = labels[1].ActualWidth; 
 
            Rect position2 = new Rect(); 
            position2.Location = labels[0].PointToScreen(new Point(0, 0)); 
            position2.Height = labels[0].ActualHeight; 
            position2.Width = labels[0].ActualWidth; 
 
            if (position1.IntersectsWith(position2)) 
            { 
                labels[1].Foreground = new SolidColorBrush(Colors.Green); 
                continue; 
            } 
 
            labels[1].Foreground = new SolidColorBrush(Colors.Red); 
        } 
    }