如何通过TextBlock查找silverlight TreeViewItem?

时间:2012-09-10 04:20:46

标签: xaml silverlight-4.0 treeview

我正试图在鼠标右键单击时选择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为null。

我试图通过名字找到控件:

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

但它返回null。

1 个答案:

答案 0 :(得分: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