1

我正在使用 WPF/MVVM/Prism 开发一个小的“有趣”项目,它的主要组件是一个 TreeView,它显示了某个路径的文件结构。ViewModel 的工作原理取自 Josh Smiths 的文章http://www.codeproject.com/Articles/28306/Working-with-Checkboxes-in-the-WPF-TreeView

我实际上需要两件事:

  1. 我想获取 TreeView-View 的已检查项目列表,显示在另一个视图(比如说列表视图)中,并且还显示它们的状态已经改变。
  2. 我想修改列表视图,然后将其反映在 TreeView 中。

不知何故,我没有找到一个好的解决方案,因为 Josh 使用的分层 ViewModel 让我很难掌握在两个 ViewModel 中都可以使用的“共享”模型。

但在陈述我的问题之前,让我们先看看我的代码:

我的“ExplorerView”使用分层数据模板,如下所示:

<UserControl x:Class="MyFunProject.Views.ExplorerView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:ViewModel="clr-namespace:MyFunProject.ViewModels"
             xmlns:prism="http://prismlibrary.com/"             
             prism:ViewModelLocator.AutoWireViewModel="True">
    <UserControl.Resources>
        <HierarchicalDataTemplate DataType="{x:Type ViewModel:ItemBaseViewModel}" ItemsSource="{Binding Children}">
            <StackPanel Orientation="Horizontal">
                <CheckBox Focusable="True" IsChecked="{Binding IsChecked}" VerticalAlignment="Center" ToolTip="{Binding Path}">
                    <TextBlock Text="{Binding Name}" />
                </CheckBox>
            </StackPanel>
        </HierarchicalDataTemplate>
    </UserControl.Resources>

    <TreeView ItemsSource="{Binding Children}" />

</UserControl>

在 Josh 的文章之后,ExplorerViewModel 将子项显示为List<CheckableItemViewModel>只有一个条目 - 实际上还有其他子目录或文件。目录本身也有孩子。

public class ExplorerViewModel : BindableBase
{
    private List<CheckableItemViewModel> childred;
    public List<CheckableItemViewModel> Children
    {
        get { return childred; }
        set { SetProperty(ref childred, value); }
    }

    public ExplorerViewModel(IExplorerModel ExplorerModel)
    {
        CheckableItemViewModel root = new CheckableItemViewModel();
        AddChildrenToNode(root, ExplorerModel.GetCheckableItems());
        root.Initialize(); // initialize children (and each children its own children, etc...)
        Children = new List<CheckableItemViewModel> { root });
    }

    private void AddChildrenToNode(CheckableItemViewModel root, IList<CheckableItem> items)
    {
        foreach(var item in items)
        {
            var child = new CheckableItemViewModel(item);
            var dirItem = item as DirectoryItem; // it's a directory and so it has childs
            if(dirItem != null)
            {
                AddChildrenToNode(child, dirItem.Items);
            }
            root.Children.Add(child);
        }
    }
}

现在回答我的问题:

  1. 如何将 my 连接CheckableItemViewModel到“某种”全局CheckableItemModel?如果我通过解析已注册的实例(统一容器)来注入构造函数,我就会遇到问题,如果我想同时拥有两个 ExplorerView(或者不是吗?),我就无法做到这一点。
  2. 如果每个人也需要构造函数参数,我该如何注入CheckableItemViewModel(这是使用参数覆盖的情况吗?)
  3. 如何获取实际选定项目的检索列表(或者我应该何时何地更新相应的模型)?
  4. 如果其中一个被更改,我如何获得“更改”标志CheckableItemViewModel

如果我错过了一块拼图,请告诉我。

感谢您的任何建议。

4

0 回答 0