Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataTemplateSelector not working if ItemContainerStyle is set

Tags:

c#

wpf

xaml

listbox

I have two Listboxes, default and custom. One uses DataTemplateSelector correctly and other just uses default DataTemplates never calling selector;

//shows correctly
<ListBox Name="testlb" ItemTemplateSelector="{StaticResource ffDataTemplateSelector}"/>

//now showing correctly (using default DataTemplates instead of selector)
<local:FFBox x:Name="myFFBox" ItemTemplateSelector="{StaticResource ffDataTemplateSelector}" ItemContainerStyle="{StaticResource FFItemStyle}" />

Both have same source

testlb.ItemsSource = CollectionViewSource.GetDefaultView(FileCollectionView);
myFFBox.ItemsSource = CollectionViewSource.GetDefaultView(FileCollectionView);

Obviously there is nothing wrong with DataTemplateSelector as it works correctly on testlb

Problem is ItemContainerStyle="{StaticResource FFItemStyle}" which I use to define overall look for each ListBoxItem, contains triggers, animation etc. If it is present the Selector does not work.

<Style x:Key="FFItemStyle" TargetType="{x:Type ListBoxItem}">
  <Setter Property="Template">
    <Setter.Value>
      <ControlTemplate TargetType="ListBoxItem">
         <Grid x:Name="mygrid">
           <ContentPresenter x:Name="ContentPresenter" 
              Content="{TemplateBinding Content}"                                          
              ContentTemplate="{TemplateBinding ContentTemplate}"/>

How do I keep ItemContainerStyle and still be able to change DataTamplates with DataTemplateSelector?

EDIT: Solved, we should keep it as this is one of those illogical and not well documented things in wpf.

like image 580
Daniel Avatar asked Oct 15 '25 16:10

Daniel


1 Answers

Got it: If you have ItemContainerStyle defined, instead of ItemTemplateSelector one needs to use ContentTemplateSelector in ContentPresenter with DataTemplateSelector.

<ContentPresenter x:Name="ContentPresenter"  Content="{TemplateBinding  Content}"
               ContentTemplateSelector="{StaticResource ffDataTemplateSelector}"
like image 116
Daniel Avatar answered Oct 18 '25 06:10

Daniel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!