0

我试图在鼠标右键单击时选择 TreeViewItem。有我的 XAML:

<TreeView x:Name="treeView" ItemsSource ="{Binding DisplayedDocuments}"  
                    SelectedItemChanged="TreeView_SelectedItemChanged" IsEnabled="True"   
                    MouseRightButtonDown="treeView_MouseRightButtonDown">
        <sdk:TreeView.ItemTemplate>
        <sdk:HierarchicalDataTemplate ItemsSource="{Binding Path=DisplayedSubItems}">
             <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Converter={StaticResource docImageConverter}}"/>
                <TextBlock Width="5"></TextBlock>
                <TextBlock Text="{Binding Caption}" 
                           MouseRightButtonDown="TextBlock_MouseRightButtonDown"/> 
             </StackPanel>  
        </sdk:HierarchicalDataTemplate>
        </sdk:TreeView.ItemTemplate>
</TreeView>

当我单击 treeViewItem 时,有时会TextBlock.MouseRightButtonDown引发而不是treeView.MouseRightButtonDown. 所以,我想通过 TextBlock_MouseRightButtonDown 中的 TextBlock 获取 treeViewItem。我试图以这种方式得到它:

    TextBlock docCaption = e.OriginalSource as TextBlock;
    StackPanel stackPanel = docCaption.Parent as StackPanel;

但 stackPanel.Parent 为空。

我试图按名称查找控件:

    TreeViewItem treeViewItem = (TreeViewItem)treeView.FindName(docCaption.Text);

但它返回null。

4

1 回答 1

1

使用 VisualTreeHelper 获取父级:http: //blogs.msdn.com/b/kmahone/archive/2009/03/29/visualtreehelper.aspx http://miguelmadero.blogspot.com.au/2008/07/use -visualtreehelper-to-navigate.html

于 2012-09-10T10:14:13.120 回答