WPF - MVVM Treeview获取所选项目[重复]

Posted

技术标签:

【中文标题】WPF - MVVM Treeview获取所选项目[重复]【英文标题】:WPF - MVVM Treeview get selected item [duplicate] 【发布时间】:2016-11-20 09:14:04 【问题描述】:

‘SelectedItem’属性是只读的,不能从标记中设置。我如何才能获得选定的项目?

        <TreeView x:Name="TreeView1"
              ItemsSource="Binding Path=Champ">

        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="x:Type self:SimpleChampionship" ItemsSource="Binding Path=Tours">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="Binding Path=Name" />
                </StackPanel>
            </HierarchicalDataTemplate>
            <HierarchicalDataTemplate DataType="x:Type self:SimpleTourClient" ItemsSource="Binding Path=Matches">
                <StackPanel Orientation="Horizontal" >
                    <TextBlock Text="Tour:" />
                    <TextBlock Text="Binding Path=NameTour" />
                    <TextBlock Text=" Matches [" />
                    <TextBlock Text="Binding Path=Matches.Count" />
                    <TextBlock Text="]" />
                </StackPanel>
            </HierarchicalDataTemplate>
            <HierarchicalDataTemplate DataType="x:Type self:SimpleMatchClient">

                <StackPanel Orientation="Horizontal" >

                    <TextBlock Text="Binding Path=Home" />
                    <TextBlock Text="Binding Path=HomeTeamGoals" />
                    <TextBlock Text=" - " />
                    <TextBlock Text="Binding Path=GuestTeamGoals" />
                    <TextBlock Text="Binding Path=Guest" />
                </StackPanel>

            </HierarchicalDataTemplate>

        </TreeView.Resources>
    </TreeView>

example treeview

需要返回选中的 SimpleMatchClient

【问题讨论】:

【参考方案1】:

试试这个。它应该可以工作。

var treeViewItem = TreeView1.ItemContainerGenerator.ContainerFromItem(SelectedItem) as TreeViewItem;

【讨论】:

以上是关于WPF - MVVM Treeview获取所选项目[重复]的主要内容,如果未能解决你的问题,请参考以下文章

WPF TreeView 泄漏所选项目

WPF MVVM TreeView SelectedItem

使用 MVVM 获取选定的 TreeViewItem

WPF TreeView IsExpanded 绑定不上的问题

TreeView —WPF—MVVM—HierarchicalDataTemplate

WPF - MVVM ???TreeView