2012-01-27 3 views
1

Я пытаюсь сортировать HierachicalDataTemplate через CollectionViewSource и класс конвертера (CollectionViewFactoryConverter), который должен быть идеальным решением для сортировки всех уровней древовидной структуры. Я использую DXTreelist из DevExpress, но я предполагаю, что это не источник моей проблемы.Конвертер никогда не вызывается при попытке сортировки HierachicalDataTemplate через CollectionViewSource и конвертер

Моя проблема: конвертер никогда не срабатывает. Я могу поставить точку останова в метод Convert или ConvertBack, но я никогда не заканчиваю там. Я не могу понять, почему нет реакции. - Может ли кто-нибудь помочь?

WPF Код:

<Window.Resources> 

    <view:CollectionViewFactoryConverter x:Key="collectionViewFactoryConverter" /> 

    <local:MyTemplateSelector x:Key="templateSelector" /> 
    <local:ContentToTreeListNodeConverter x:Key="contentToTreeListNodeConverter"/> 

    <CollectionViewSource Source="{Binding Path=Data, Mode=TwoWay}" x:Key="cvsRoot"> 
     <CollectionViewSource.SortDescriptions> 
      <scm:SortDescription PropertyName="Name" /> 
     </CollectionViewSource.SortDescriptions> 
    </CollectionViewSource> 

    <DataTemplate x:Key="StandardTemplate"> 
     <TextBlock Text="Template Not Found!" /> 
    </DataTemplate> 

    <HierarchicalDataTemplate x:Key="RootTemplate" 
     ItemsSource="{Binding RefA, Converter={StaticResource collectionViewFactoryConverter}, ConverterParameter=Row.Name}"> 
     <TextBlock Text="{Binding Row.Name}" /> 
    </HierarchicalDataTemplate> 

    <!--Code below is working, but results are unsorted--> 
    <!--<HierarchicalDataTemplate x:Key="RootTemplate" ItemsSource="{Binding RefA}">         
     <TextBlock Text="{Binding Row.Name}" /> 
    </HierarchicalDataTemplate>--> 

    <HierarchicalDataTemplate x:Key="ModelATemplate" ItemsSource="{Binding RefB}"> 
     <TextBlock Text="{Binding Row.Name}" /> 
    </HierarchicalDataTemplate> 

    <HierarchicalDataTemplate x:Key="ModelBTemplate"> 
     <TextBlock Text="{Binding Row.Name}" /> 
    </HierarchicalDataTemplate>   

</Window.Resources> 

Код TreelistControl:

<dxgcore:TreeListControl Name="treeListControl" 
     DesignTimeShowSampleData="False" 
     ItemsSource="{Binding Source={StaticResource cvsRoot}}" 
     Grid.ColumnSpan="2" Margin="123,0,0,0" ItemsSourceChanged="treeListControl_ItemsSourceChanged"> 

     <dxg:TreeListControl.View> 
      <dxg:TreeListView Name="tlvList" 
      IsColumnMenuEnabled="False" 
      AllowPerPixelScrolling="True" 
      AutoWidth="True" 
      ShowHorizontalLines="False" 
      ShowVerticalLines="False" 
      ShowIndicator="False" 
      ShowFocusedRectangle="False" 
      NavigationStyle="Row" 
      TreeLineStyle="Solid"         
      FixedLineWidth="1" 
      FilterEditorShowOperandTypeIcon="True" 
      DataRowTemplateSelector="{StaticResource templateSelector}" 
      TreeDerivationMode="HierarchicalDataTemplate" 
      FocusedNode="{Binding HierarchicalFilterSelection, Mode=OneWayToSource}" 
     > 
      </dxg:TreeListView> 
     </dxg:TreeListControl.View> 
    </dxgcore:TreeListControl> 

конвертер Класс:

[ValueConversion(typeof(System.Collections.IList), typeof(System.Collections.IEnumerable))] 

public class CollectionViewFactoryConverter : IValueConverter 
{ 
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     System.Collections.IList collection = (System.Collections.IList)value as System.Collections.IList; 
     ListCollectionView view = new ListCollectionView(collection); 
     SortDescription sort = new SortDescription(parameter.ToString(), ListSortDirection.Ascending); 
     view.SortDescriptions.Add(sort); 
     return view; 
    } 

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
     return null; 
    } 
} 

Селектор шаблон выглядит следующим образом КСТАТИ:

public class MyTemplateSelector : DataTemplateSelector 
{ 
    public override DataTemplate SelectTemplate(object item, DependencyObject container) 
    { 
     DataTemplate template = null; 
     if (item != null) 
     { 
      FrameworkElement element = container as FrameworkElement; 
      if (element != null) 
      { 

       string templateName = "StandardTemplate"; 
       DevExpress.Xpf.Grid.TreeList.TreeListRowData itemAsTreelistRowData = null; 

       if (item is DevExpress.Xpf.Grid.TreeList.TreeListRowData) 
       { 
        itemAsTreelistRowData = item as DevExpress.Xpf.Grid.TreeList.TreeListRowData; 
       } 

       if (itemAsTreelistRowData.Row is Root) 
       { 
        templateName = "RootTemplate"; 
       } 
       else 
        if (itemAsTreelistRowData.Row is ModelA) 
        { 
         templateName = "ModelATemplate"; 
        } 
        else 

         if (itemAsTreelistRowData.Row is ModelB) 
         { 
          templateName = "ModelBTemplate"; 
         } 

       template = element.FindResource(templateName) as DataTemplate; 
      } 
     } 
     return template; 
    } 

} 
+0

Я не вижу ваш конвертера используется в любом месте .... Я вижу, вы привязку к 'TemplateSelector', но нет код для использования конвертера для вашего TreeListView – Rachel

+0

Теперь я добавил код TemplateSelector. Фактические HierarchicalDataTemplates действительно инициируются - если я изменяю, например, Row.Name к чему-то еще, я вижу изменение. Но конвертер, по-видимому, не может быть вызван в этот момент ... – Artimidor

ответ

0

Попробуйте позвонить праву конвертера в связывании для ItemsSource в вашем TreeListControl:

ItemsSource="{Binding Source={StaticResource cvsRoot}, Converter={StaticResource collectionViewFactoryConverter}}" 
+0

В этом случае конвертор запускается, но я не могу сортировать дочерние узлы с ним сейчас, боюсь. Мне всегда нужно сортировать узлы следующего уровня (RefA, RefB и т. Д.), Поэтому конвертер каким-то образом должен работать на разных уровнях. И он неуклонно отказывается это делать. :( P.S. Теперь я добавил код TemplateSelector, где принято решение о выборе HierarchicalDataTemplate. Эти шаблоны действительно запускаются, но похоже, что я не могу использовать конвертер на этом этапе. – Artimidor