绑定到ObservableCollection的WPF TreeView在添加时不会更新

时间:2013-09-12 09:21:45

标签: wpf xaml treeview mvvm-light observablecollection

浏览了类似的答案,但我找不到问题。

我正在使用MvvmLight,并将WPF TreeView绑定到ViewModel中的ObservableCollection。 树显示正常,但如果我稍后将成员添加到ObservableCollection,则树不会刷新。

以下是代码:

// the data type that represents a tree node
public class FurnitureTreeNode : GalaSoft.MvvmLight.ViewModelBase
{
    public string Name { get; private set; }
    public object Data { get; private set; }
    public ObservableCollection<FurnitureTreeNode> ChildNodes { get; set;}
    public Furniture(string Name, ObservableCollection<FurnitureTreeNode> ChildNodes, object Data)
    {
        this.Name = Name;
        this.ChildNodes = ChildNodes;
        this.Data = Data;
    }
}

public class FurnituresViewModel : GalaSoft.MvvmLight.ViewModelBase
{
    public ObservableCollection<FurnitureTreeNode> TopFurnitureNodes { get; set; }
    public ObservableCollection<FurnitureTreeNode> ChairNodes { get; set; }

    public FurnituresViewModel()
    {
        // initialize the top level furnitures collection
        TopFurnitureNodes = new ObservableCollection<FurnitureTreeNode>();

        // add two children
        TopFurnitureNodes.Add(new FurnitureTreeNode("Tables", null, null);
        TopFurnitureNodes.Add(new FurnitureTreeNode("Chairs", null, null);

        // add Beds only when they're ready
        BedsManager.ImportsSatisfied += AddBedsNode;
    }

以下运行正常,使用Beds节点更新集合,但它不会反映在TreeView中:

    void AddBedsNode( object sender, EventArgs e )
    {
        Task.Run(() =>
        {
            TopFurnitureNodes.Add(new FurnitureTreeNode("Beds", null, null);
        }
        );
    }
}

这是XAML:

<TreeView Name="FurnituresTreeView" ItemsSource="{Binding TopFurnitureNodes}">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Path=ChildNodes}" DataType="x:Type FurnitureTreeNode">
            <TextBlock Text="{Binding Path=Name}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
</TreeView>

谢谢!

2 个答案:

答案 0 :(得分:1)

安德鲁,

请尝试替换

    Task.Run(() =>
    {
        TopFurnitureNodes.Add(new FurnitureTreeNode("Beds", null, null);
    }
    );

使用:

TopFurnitureNodes.Add(new FurnitureTreeNode("Beds", null, null);

让我们知道这有帮助。

还请确保将ViewModel绑定到View。

答案 1 :(得分:0)

尝试在视图模型中实施INotifyPropertyChanged界面,并在更新时PropertyChanged参数值为PropertyName参数值TopFurnitureNodes

Task.Run(() =>
{
    TopFurnitureNodes.Add(new FurnitureTreeNode("Beds", null, null);
    RaisePropertyChanged("TopFurnitureNodes");
});

你不应该真的需要这样做,但它应该有效。