为什么listview项目不会出现在命中测试结果中?

时间:2014-02-26 22:02:25

标签: c# wpf xaml

所以我在这里关注这个例子:http://msdn.microsoft.com/en-us/library/ms752097%28v=vs.110%29.aspx

为了测试列表视图中的项目。但是,它给了我controltemplate中的项目而没有给我实际的listview项目。我不确定为什么会发生这种情况,或者我是如何让它进行测试,看看鼠标是否在listviewitems之上。

  hitResultsList.Clear();
  Point pt = e.GetPosition((UIElement)sender);

  // Perform the hit test against a given portion of the visual object tree.
  VisualTreeHelper.HitTest(canv, null, new HitTestResultCallback(MyHitTestResult),
    new PointHitTestParameters(pt)
    );

它从我的controltemplate返回边框scrollviewer和网格,但不返回scrollviewer中的实际项目。

  <ControlTemplate>
    <Grid 
      Background="{TemplateBinding Background}"
      >
      <Grid.RowDefinitions>
        <RowDefinition 
          Height="{Binding GraphHeight, Source={x:Static DaedalusGraphViewer:SettingsManager.AppSettings},
                  Converter={StaticResource GridLengthConverter}}"
          />
        <RowDefinition Height="*"/>
        <RowDefinition Height="18" />
      </Grid.RowDefinitions>
      <Border
        Grid.ZIndex="1"                    
        Grid.Row="0"
        BorderBrush="{TemplateBinding BorderBrush}"
        BorderThickness="{TemplateBinding BorderThickness}"
        >
        <Grid>
          <TextBlock 
            Foreground="{TemplateBinding Foreground}"
            VerticalAlignment="Center"
            HorizontalAlignment="Center"
            Text="Signal Names"
            />
        </Grid>
      </Border>
      <Canvas>
        <Line 
          Grid.ZIndex="2"
          x:Name="SelectedItemUnderline"
          Stroke="Black"
          StrokeThickness="3"
          Visibility="Collapsed"
          />
      </Canvas>
      <ScrollViewer 
        Grid.ZIndex="1"                    
        x:Name="SignalNameScrollViewer" 
        Grid.Row="1" Grid.RowSpan="2" 
        CanContentScroll="False"
        VerticalScrollBarVisibility="Hidden" HorizontalScrollBarVisibility="Visible" 
        >
        <ItemsPresenter />
      </ScrollViewer>
    </Grid>
  </ControlTemplate>

1 个答案:

答案 0 :(得分:2)

正如您所说,您当前的点击测试返回GridScrollViewer,您可以使用FrameworkElement.TemplatedParent属性找到ListViewItem。即。

HitTestResult hitTestResult; // TODO either from callback or result
var fe = hitTestResult.VisualHit as FrameworkElement;
if(fe != null)
{
    var listViewItem = fe.TemplatedParent as ListViewItem;
    if(listViewItem != null)
    {
        // TODO Do something with the ListViewItem
    }
}