0

我的程序中有一个TreeView需要从 MVVM 结构的数据模型级别实现的程序。它需要以这种方式实现,以便程序将其保存在数据中。我的程序在不同的窗口之间切换,如果树只深入到视图模型级别,则在这些切换期间树会丢失。我有数据工作,但视图没有回报(我最近似乎遇到了很多问题)。

我将在这里发布我的过程。请记住这个的结构TreeView

-Usercontrol(包含TreeView)->ViewModel->Model(TreeView需要存放在这个Model中)

-TreeView->ViewModel->Model

用户控制模型:

public BlockingTreeViewModel _blockDataTree;

public BlockingDatabaseModel() { }

public BlockingTreeViewModel BlockDataTree {...}

用户控件视图模型:

public BlockingDatabaseModel _blockingModel;

public BlockingDatabaseViewModel(BlockingDatabaseModel model, BlockingTreeViewModel blockingTreeView)
{
    BlockingModel = model;
    BlockingModel.BlockDataTree = blockingTreeView;
}

public BlockingDatabaseModel BlockingModel {...}
public BlockingTreeViewModel BlockingTree //PROXY PROPERTY
{
    get { return BlockingModel.BlockDataTree; }
    set
    {
        BlockingModel.BlockDataTree = value;
        NotifyPropertyChange(() => BlockingTree);
    }
}

用户控件.xaml:

<TreeView ItemsSource="{Binding BlockingModel.BlockDataTree.BlockTree}" ... />

现在,添加到此之后,TreeView我可以在调试时看到新节点,但视图没有显示任何新创建的节点。据我对这种情况的理解,这是正确实施的,应该可以正常工作。请帮助我了解为什么视图不会在 UserControl 中显示此树。

现在上述更改已应用于我的 xaml,树节点已创建并显示。但是,每当我更改屏幕时,这些节点就会消失。这意味着我TreeView在这个 MVVM 结构中仍然有问题。

*注意: 的属性TreeView是代理属性,只是因为它使我的代码在程序的其他区域更简单。不过,这不应该影响我正在做的事情。

更新1:

调试期间我的“Locals”窗口的屏幕截图。这表明我能够在TreeView.

在此处输入图像描述

更新 2:更新了 xaml 中的绑定

4

1 回答 1

0

如果您要切换的屏幕包含您不应该在每次查看时都TreeViews创建一个新屏幕,因为它会重置当前屏幕。ObservableCollectionTreeView

我这样说是因为我每次切换回ViewModel 时都会ObservableCollection在我的 ViewModel 中创建一个新的。TreeView

我的构造函数TreeViewViewModel

public BlockingTreeViewModel()
{
    BlockTree = new ObservableCollection<BlockingTreeModel>();
}

反而...:

//Pass the ObservableCollection from a different area of your code each time
//you use BlockingTreeViewModel so that you don't overwrite it.
public BlockingTreeViewModel(ObservableCollection<BlockingTreeModel> treeCollection)
{
    BlockTree = treeCollection;
}
于 2013-11-13T21:57:51.133 回答