2016-08-08 4 views
0

Я хотел бы получить образцы данных, которые будут отображаться в моем Treeview во время разработки. My Treeview содержит вложенные Treeviews и CollectionViewSources.Связывание дерева древовидного дизайна с группами CollectionViewSources и HierarchicalDataTemplate

Я хотел бы узнать, как отобразить вложенные Treeviews (показывается только первый из 3 уровней узлов).

О Treeview

Вот что я понял, до сих пор:

Мой Treeview содержит иерархические данные (состояния объектов (например, "Ready")> Дата (т.е. «8/8/. 16")> Name (например, "яблоки"), но я могу получить только один

Treeview подкреплена:

  • ObjectTreeviewViewModel (в ObservableColle ие)
  • CollectionViewSource к группе StateDisplay (+ сортировки)
  • Другой CollectionViewSource к группе ObjectDateDisplay

Текущий статус

ObjectTreeview показывает только один уровень узлов во время разработки, когда Я ожидаю 3 уровня узлов.

Treeview (WPF) only shows 1 level of nodes in design time- should show 3

Мои Stack

Я строю приложение WPF на .net 4.5, с помощью Visual Studio 2015.

Код

XAML

<UserControl x:Class="myproject.app.views.MainWindow.ObjectTreeview" 
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
          xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
          xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
          mc:Ignorable="d" 
          d:DesignHeight="300" d:DesignWidth="300" 
          DataContext="{Binding RelativeSource={RelativeSource Self}}" 
          > 

      <UserControl.Resources> 

        <ResourceDictionary> 
          <ResourceDictionary.MergedDictionaries> 
            <ResourceDictionary Source="../../resources/MainWindow/ObjectTreeviewResources.xaml"></ResourceDictionary> 
          </ResourceDictionary.MergedDictionaries> 
        </ResourceDictionary> 

      </UserControl.Resources> 

      <TreeView x:Name="Treeview" 
             ItemsSource="{Binding Source={StaticResource ObjectStateCollectionViewSource}, Path=Groups}" 
             ItemTemplate="{Binding Source={StaticResource ObjectStateTemplate}}"> 
      </TreeView> 

    </UserControl> 

XAML Ресурсы

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
              xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=WindowsBase" 
              xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
              xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
              xmlns:pf="clr-namespace:System.ComponentModel;assembly=PresentationFramework" 
              xmlns:mainWindow="clr-namespace:myproject.app.viewmodels.MainWindow" 
              mc:Ignorable="d"> 

      <!-- I.e. Level-3 Node (i.e. Leaf nodes) --> 
      <DataTemplate x:Key="ObjectTreeviewNode"> 
        <TextBlock Text="{Binding ObjectNameDisplay}"/> 
      </DataTemplate> 


      <!-- Initial Grouping: Group by object states --> 
      <CollectionViewSource x:Key="ObjectStateCollectionViewSource" 
                 Source="{Binding Path=ObjectTreeviewViewModel.TreeviewCollection}" 
                 d:DesignSource="{d:DesignData Source=ObjectTreeviewDesignTimeData.xaml}" 
                 > 
        <CollectionViewSource.GroupDescriptions> 
          <PropertyGroupDescription PropertyName="StateDisplay"/> 
        </CollectionViewSource.GroupDescriptions> 
        <CollectionViewSource.SortDescriptions> 
          <componentModel:SortDescription PropertyName="StateEnum" /> 
          <componentModel:SortDescription PropertyName="ObjectDate" /> 
          <componentModel:SortDescription PropertyName="ObjectNameDisplay" /> 
        </CollectionViewSource.SortDescriptions> 
      </CollectionViewSource> 

      <!-- I.e. Level-2 Node (i.e. mid-nodes) --> 
      <HierarchicalDataTemplate x:Key="ObjectDateTemplate"> 
        <TreeView BorderThickness="0"> 
          <TreeViewItem Header="{Binding Path=Name}" 
                 ItemsSource="{Binding Path=Items}" 
                 d:DataContext="{Binding Path=Items}" 
                 ItemTemplate="{StaticResource ResourceKey=ObjectTreeviewNode}" 
                 IsExpanded="True"/> 
        </TreeView> 
      </HierarchicalDataTemplate> 

      <!-- I.e. Level-1 Node (i.e. Root nodes) --> 
      <HierarchicalDataTemplate x:Key="ObjectStateTemplate" > 
        <TreeView BorderThickness="0"> 

          <TreeView.Resources> 

            <!-- Sub-grouping: Group by object dates (This needs to be nested in this Treeview.Resources) --> 
            <CollectionViewSource x:Key="ObjectDateCollectionViewSource" 
                       Source="{Binding Path=Items}" 
                       d:DesignSource="{Binding Path=Items}" 
                       > 

              <CollectionViewSource.GroupDescriptions> 
                <PropertyGroupDescription PropertyName="ObjectDateDisplay"/> 
              </CollectionViewSource.GroupDescriptions> 

            </CollectionViewSource> 

            <!-- [This and all children] Hide the light-grey inactive background --> 
            <SolidColorBrush x:Key="{x:Static SystemColors.InactiveSelectionHighlightBrushKey}" Color="Transparent" /> 

          </TreeView.Resources> 

          <TreeViewItem Header="{Binding Path=Name}" 
                 ItemsSource="{Binding Source={StaticResource ObjectDateCollectionViewSource}, Path=Groups}" 
                 ItemTemplate="{StaticResource ObjectDateTemplate}" 
                 IsExpanded="True"/> 

        </TreeView> 
      </HierarchicalDataTemplate> 
    </ResourceDictionary> 

Code-Behind

using System.Windows.Controls; 
    using myproject.app.viewmodels.MainWindow; 
    using myproject.lib.enumerations; 

    namespace myproject.app.views.MainWindow 
    { 
      /// <summary> 
      /// Interaction logic for ObjectTreeview.xaml 
      /// </summary> 
      public partial class ObjectTreeview : UserControl 
      { 
        public ObjectTreeviewViewModel ObjectTreeviewViewModel { get; private set; } = new ObjectTreeviewViewModel(); // this is a ObservableCollection<ObjectViewModel> 

        public ObjectTreeview() 
        { 
          InitializeComponent(); 
        } 

        /// <summary> 
        ///  Load object for an objectStateGroup (a set of ObjectStates) into the collection that backs the treeview. 
        /// </summary> 
        /// <param name="objectStateGroup">The objectStateGroupsEnum to load.</param> 
        public void LoadObjectStateGroup(objectStateGroupsEnum objectStateGroup) 
        { 
          ObjectTreeviewViewModel.LoadobjectStateGroup(objectStateGroup); 
        } 
      } 
    } 

ответ

0

Я нашел обходной путь к моей проблеме.

Этот вопрос

Проблема была с внутренней CollectionViewSource (тот, который контролировал середину 3 узлов). Его внешний вид показывал только внешний CollectionViewSource.

Временное связывание с проектом не может использовать тот же Path=Items, что и время выполнения.

<CollectionViewSource x:Key="ObjectDateCollectionViewSource" 
         Source="{Binding Path=Items}" 
         d:DesignSource="{Binding Path=Items}"> 

       <CollectionViewSource.GroupDescriptions> 
           <PropertyGroupDescription PropertyName="ObjectDateDisplay"/> 
       </CollectionViewSource.GroupDescriptions> 

</CollectionViewSource> 

Решение

Обновление д: DesignSource для загрузки из примера файла XAML (тот же, который мы используем выше) с Source=ObjectTreeviewDesignTimeData.xaml.

<CollectionViewSource x:Key="ObjectDateCollectionViewSource" 
          Source="{Binding Path=Items}" 
          d:DesignSource="{d:DesignData Source=ObjectTreeviewDesignTimeData.xaml}"> 

      <CollectionViewSource.GroupDescriptions> 
        <PropertyGroupDescription PropertyName="ObjectDateDisplay"/> 
      </CollectionViewSource.GroupDescriptions> 

    </CollectionViewSource> 

После установки D: DesignSource и повторного здания, 3 уровня узлов начали появляться во время разработки. Я подтвердил, что проблема с привязкой времени разработки была с внутренним CollectionViewSource.

Достаточного Обход

Пути связывания с тем же словарем в наружной и внутренней CollectionViewSources, избыточные данные генерируются. (Словарь загружается несколько раз, для каждого поддерева.) Однако это нормально, так как я в режиме конструктора, и мне просто нужны данные заполнителя.

Лучшим решением было бы найти способ заставить внутреннюю часть CVS d:DesignerSource="{BETTER_SOLUTION_HERE}" работать с использованием той же коллекции, что и внешние CVS.

Смежные вопросы