为什么WPF TreeViewItem.Expanded" sender"传递TreeView而不是TreeViewItem?

时间:2016-07-08 03:21:42

标签: wpf treeview

如何访问正在展开的TreeViewItem(或更确切地说是对象)?根据我的估计"发件人"从事件处理程序应该是TreeViewItem而不是TreeView。我希望在扩展时对绑定到TreeViewItem的对象采取行动。

return createsPromiseA()
  .then((a) => bluebird.promisify(takesNodebackB)(a))
  .then((b) => createsPromiseC());

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525"
    Loaded="Window_Loaded">
<StackPanel>
    <TreeView x:Name="treeView" HorizontalAlignment="Left" VerticalAlignment="Top" 
              TreeViewItem.Expanded="treeViewItem_Expanded" >
        <TreeView.ItemTemplate>
            <HierarchicalDataTemplate ItemsSource="{Binding}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Name}" />
                </StackPanel>
            </HierarchicalDataTemplate>
        </TreeView.ItemTemplate>
    </TreeView>
</StackPanel>

1 个答案:

答案 0 :(得分:0)

使用TreeViewItem.Selected事件。选定的事件冒泡到树视图(TreeViewItem本身在设计时不存在,因为我们使用的是HierarchicalDataTemplate)。

事件可以在XAML中捕获,如下所示:

<TreeView TreeViewItem.Selected="TreeViewItemSelected" .../> 

然后可以在事件中设置所选的最后一个TreeViewItem:

private void TreeViewItemSelected(object sender, RoutedEventArgs e)
{
    TreeViewItem tvi = e.OriginalSource as TreeViewItem;

    // set the last tree view item selected variable which may be used elsewhere as there is no other way I have found to obtain the TreeViewItem container (may be null)
    this.lastSelectedTreeViewItem = tvi;

    ...
 }