2015-08-31 59 views
0
  <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

爲什麼不能將hitResultsList [1]投射到邊界? ((Border)hitResultsList [1])。名稱會給你這個邊界的名稱 – VMaleev

+0

有沒有什麼特別的原因讓你點擊鼠標來測試點?你知道,用WPF你不必做任何這個,對吧? –

+0

不,我是WPF的新手,請告知更好的方法來做到這一點 – user2192101

回答

0

嘗試

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

打印的項目的名稱到控制檯。輸出應該在Visual Studio輸出窗口中可見。