我点击了哪个对象?

时间:2015-08-31 09:47:54

标签: c# wpf

           <Border Name="firstborder"
                Grid.Column="0"
                Grid.Row="0"
                BorderBrush="Black"
                BorderThickness="1">
            </Border>
            <Border Name="secondborder"
                Grid.Column="1"
                Grid.Row="0"
                BorderBrush="Black"
                BorderThickness="1">
            </Border>
                <Border Name="thirdborder"
                Grid.Column="0"
                Grid.Row="1"
                BorderBrush="Black"
                BorderThickness="1">
            </Border>
            <Border Name="fourthborder"
                Grid.Column="1"
                Grid.Row="1"
                BorderBrush="Black"
                BorderThickness="1">
            </Border>

我有以上四个Border对象。我想使用视觉命中测试来确定我点击了哪一个。

        // Clear the contents of the list used for hit test results.
        hitResultsList.Clear();

        // Set up a callback to receive the hit test result enumeration.
        VisualTreeHelper.HitTest(this, null,
            new HitTestResultCallback(MyHitTestResult),
            new PointHitTestParameters(point));

        // Perform actions on the hit test results list. 
        if (hitResultsList.Count > 0)
        {
            Console.WriteLine("Number of Visuals Hit: " + hitResultsList.Count);
        }
        Visual visual = hitResultsList[1];
        Console.WriteLine("To string " + visual.ToString()); 
        if ( visual.Equals(secondborder) )
            Console.WriteLine("2nd border ");
        if (visual.Equals(firstborder))
            Console.WriteLine("first border ");
        if (visual.Equals(thirdborder))
            Console.WriteLine("third border ");
        if (visual.Equals(fourthborder))
            Console.WriteLine("4th border "); 

调试器告诉我,视觉命中测试在hitResultsList [1]中返回了一个Border元素。现在我只想确定四个Border对象中的哪一个。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

尝试

Console.WriteLine((Border)visual.Name);

将项目名称打印到控制台。输出应该在Visual Studio输出窗口中可见。