TreeView不存储预期状态

时间:2013-06-27 19:06:23

标签: c# wpf treeview wpf-controls

我遇到了以下不明白的行为。我的数据正确显示在TreeView中,如下所示。

Sport
  > BaseBall
    > Apparel
    > Equiptment
        Glove
        Bat
  > Football
    > Helmet
  > Soccer

但是,当我点击任何节点时,底层节点数据就是它的第一个子节点。

    Node Clicked            Actual Data
-------------------------------------------
    Sport                       Baseball
    Baseball                    Apparel
    Football                    Helmet
    Bat                         null

我在网上和书中看过很多例子,但我看不出这个问题;我相信这很简单。

编辑我已经在视觉上检查了调试器中的每个节点,并使用了Mathew MacDonald在C#2010中的Pro WPF中的一个方便的小代码片段,它实际上显示了每个控件的类型和值。树视图。

编辑我已将初始代码替换为可重现问题的实际完整应用程序。这是我能想到的最简单的例子。

代码(删除了不相关的部分):

<Application x:Class="WpfApplication1.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:this="clr-namespace:WpfApplication1"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <this:MainWindowViewModel x:Key="ViewModel:MainWindow"></this:MainWindowViewModel>
    </Application.Resources>
</Application>

-

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:this="clr-namespace:WpfApplication1"
        Title="MainWindow" Height="350" Width="525"
        DataContext="{StaticResource ViewModel:MainWindow}">
    <TreeView x:Name="theTree" ItemsSource="{Binding Path=OrgChart}"
              MouseUp="theTree_MouseUp">
        <TreeView.Resources>
            <HierarchicalDataTemplate ItemsSource="{Binding Path=Subordinates}" DataType="{x:Type this:OrgChartNodeViewModel}">
                <TextBlock Text="{Binding Path=Position.Title}"></TextBlock>
            </HierarchicalDataTemplate>
        </TreeView.Resources>
    </TreeView>
</Window>

-

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void theTree_MouseUp(object sender, MouseButtonEventArgs e)
    {
        Stack<DependencyObject> stack = new Stack<DependencyObject>();
        var it = e.OriginalSource as DependencyObject;
        while (it != null)
        {
            it = VisualTreeHelper.GetParent(it);
            stack.Push(it);
        }

        int level = 0;
        while (stack.Any())
        {
            Debug.Write("".PadLeft(level++));
            it = stack.Pop();
            if (it is TreeViewItem)
            {
                var item = it as TreeViewItem;
                OrgChartNodeViewModel vm = ((OrgChartNodeViewModel)((TreeViewItem)it).Items.CurrentItem);
                if (vm != null)
                    Debug.WriteLine(vm.Position.Title);
            }
            else
            {
                Debug.WriteLine(it);
            }
        }
    }
}

-

public class MainWindowViewModel
{
    public List<OrgChartNodeViewModel> OrgChart { get; set; }

    public MainWindowViewModel()
    {
        Position ceo = new Position { Title = "CEO" };
        Position vp = new Position { Title = "VP" };
        Position boss = new Position { Title = "Boss" };
        Position worker = new Position { Title = "Worker" };

        OrgChartNodeViewModel root;
        OrgChartNodeViewModel node = new OrgChartNodeViewModel { Position = ceo };
        OrgChartNodeViewModel child = new OrgChartNodeViewModel { Position = vp };
        root = node;
        node.Subordinates.Add(child);
        node = child;
        child = new OrgChartNodeViewModel { Position = boss };
        node.Subordinates.Add(child);
        node = child;
        child = new OrgChartNodeViewModel { Position = worker };
        node.Subordinates.Add(child);

        OrgChart = new List<OrgChartNodeViewModel> { root };
    }
}

-

public class OrgChartNodeViewModel
{
    public Position Position { get; set; }
    public List<OrgChartNodeViewModel> Subordinates { get; set; }

    public OrgChartNodeViewModel()
    {
        Subordinates = new List<OrgChartNodeViewModel>();
    }
}

-

public class Position
{
    public string Title { get; set; }
}

这是我机器上的输出......

enter image description here

1 个答案:

答案 0 :(得分:3)

尝试切换

OrgChartNodeViewModel vm = ((OrgChartNodeViewModel)((TreeViewItem)it).Items.CurrentItem);

OrgChartNodeViewModel vm = ((OrgChartNodeViewModel)viewItem.DataContext);

在你的while循环中,你希望TreeViewItem.DataContext而不是Items.CurrentItem指向它的孩子(并且只有一个存在,直到首先扩展)。因此,为什么你会看到副总裁而不是CEO。

我会将整个功能切换为:

private void theTree_MouseUp(object sender, MouseButtonEventArgs e) {
  var clickedItem = e.OriginalSource as FrameworkElement;
  if (clickedItem == null)
    return;
  var chartNode = clickedItem.DataContext as OrgChartNodeViewModel;
  if (chartNode != null)
    Debug.WriteLine(chartNode.Position.Title);
}

迭代通过Visual-Tree获得TreeViewItem。 {x}在您的xaml设置中继承,因此不妨使用它来保存冗余工作。