0

我正在使用 TreeView 和 HierarchicalDataTemplate 来显示从 web 服务返回的分层列表。根据搜索条件,此列表可能会变得很长,并且有几个嵌套级别。向用户显示各种“地图”会很有用,这样他们就可以在这个列表中看到他们相对于顶层的位置。用于创建层次结构的模型如下所示:

public class IndexEntry
{
    public int Score { get; set; }
    //More properties that define attributes of this class

    //Child objects of the hierarchy are stored in this property
    public List<IndexEntry> SubEntries { get; set; }      
}

如您所见,层次结构是使用 IndexEntry 类型列表构建的。

ViewModel 看起来像这样:

public class IndexEntriesViewModel
{
    //TreeView ItemsSource is bound to this collection
    public ObservableCollection<IndexEntry> IndexList { get; set; } 
    //More properties to define the ViewModel
}

如您所见,TreeView 的 ItemsSource 将绑定到 IndexEntry 类型的 ObservableCollection。我看不到任何明显的方式来访问父对象,就像现在一样。我正在考虑在模型中添加另一个属性的选项,该属性将直接指向该特定条目的父对象。这最终将允许我在层次结构中上下走动,并在需要时抓住我喜欢的东西。

所以,问题是 - 谁能想到更好的方法来实现这一点?我缺少的 TreeView 本身是否有一个属性可以提供这种能力?

4

2 回答 2

1

在 2009 年 7 月发布的 Silverlight Toolkit 中有一个简单的解决方案,即 TreeViewExtensions 中的 GetParentItem 扩展方法。

  1. 下载并安装Silverlight 工具包

  2. 添加对 System.Windows.Controls.Toolkit 的引用(可在 C:\Program Files (x86)\Microsoft SDKs\Silverlight\v3.0\Toolkit\Jul09\Bin 中找到)。

  3. 从您想要获取父级的方法(我将使用 SelectedItemChanged 事件作为示例):

    private void OrgTree_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        if (e.NewValue != null)
        {
            var parent = ((TreeView)sender).GetParentItem(e.NewValue);
            if (parent != null)
            {
                Status.Text = "Parent is " + parent.ToString();
            }
        };
    }
    

那里隐藏着很多很棒的扩展,我鼓励您探索设置选定项目、扩展节点和获取项目容器。

于 2009-09-01T21:34:37.930 回答
0

TreeViewExtensions 可以帮助我找到 treeviewitem 和父对象。最后查看底部页面。

http://silverlight.net/forums/t/65277.aspx

于 2009-08-24T03:06:29.657 回答