桥接IEnumerable集合将其绑定到WPF中的TreeView

时间:2018-04-19 11:35:30

标签: c# wpf treeview ienumerable hierarchicaldatatemplate

我一直在寻找这个问题的解决方案,但经过这么多的研究,我仍然无法找到一个优雅的解决方案。最后,我决定在此提出专家意见。

这是一个WPF应用程序,我创建了我的域/模型类,如:

public abstract class Node : Entity
{
    private string _name;
    public string Name
    {
        get { return _name; }
        set { SetProperty(ref _name, value); }
    }

    public Node Parent { get; set; }

    private List<Node> _children = new List<Node>();
    public IEnumerable<Node> Children => _children.AsEnumerable();

    public void AddChild(Node node)
    {
        _children.Add(node);
    }

    public void RemoveChild(Node node)
    {
        _children.Remove(node);
    }

    public void MoveUp(Node node)
    {
        var index = _children.IndexOf(node);
        Move(index, index - 1);
    }

    public void MoveDown(Node node)
    {
        var index = _children.IndexOf(node);
        Move(index, index + 1);
    }
}

根据此域名,Node类具有父子关系。

此处需要注意的重点是Children集合类型公开为IEnumerable以封装它以避免对我的集合进行不必要的更改。我想将此集合绑定到TreeView控件以显示层次结构的N级。

<HierarchicalDataTemplate x:Key="ContainerTemplate" 
                          DataType="{x:Type fsx:Node}" 
                          ItemsSource="{Binding Children}">
    <StackPanel Orientation="Horizontal">
        <TextBlock Text="{Binding Name}" />
    </StackPanel>
</HierarchicalDataTemplate>

<fsx:TreeViewTemplateSelector x:Key="TreeViewTemplateSelector"
                              ContainerTemplate="{StaticResource ContainerTemplate}" />

<TreeView x:Name="TreeViewNodes"
          ItemsSource="{Binding Nodes}" 
          ItemTemplateSelector="{StaticResource TreeViewTemplateSelector}">
</TreeView>

想象一下,绑定到TreeView Nodes属性的ItemSource在ViewModel中是ObservableCollection,它从模型中获取数据。

我想允许UI操作,例如添加和删除节点以及上下移动它们,相应地我想在我的域对象中更新这些操作。现在的问题是,由于我的收藏不是ObservableCollection,我正在执行的任何操作都没有反映在UI中。

问题是如何使所有工作立即在UI上显示操作结果以及有效地更新场景背后的域名?

注意:如果需要,我会更新问题以提供更多详细信息!

0 个答案:

没有答案