WPF - MVVM Treeview获取所选项目

时间:2016-07-17 19:43:20

标签: wpf xaml mvvm treeview selecteditem

'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

2 个答案:

答案 0 :(得分:-1)

试试这个。它应该工作。

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

答案 1 :(得分:-1)

工人,我添加SelectedItemChanged="TreeView1_OnSelectedItemChanged"

private void TreeView1_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
    var dc = DataContext as MainWindowViewModel;
    try
    {
        dc.SelectedMatch = (SimpleMatchClient)e.NewValue;
    }
    catch (Exception)
    {
        return;
    }

}

有效,但我认为这不是一个好的解决方案