WPF Templates. Template Selector does not receive item

333 Views Asked by At

My current problem is that i have two templates which should be selected via a template selector. I have defined two datatemplates. Each containing different stackPanel, different in the sense that the count of the containing elements differs.

But in my Template Selector i cannot select one of the templates because the item given to the SelectTemplate method is always null.

I assume have not understood how templates do work in wpf. The examples you see on microsfts

Here you can see how i defined my datatemplates


 <UserControl.Resources>
        <DataTemplate x:Key="Any">
            <StackPanel Orientation="Vertical">
                 <Label>Test</Label>
                 <Label>Test</Label>
            </StackPanel>
        </DataTemplate>
        <DataTemplate x:Key="Non" >
            <StackPanel Orientation="Vertical">
                <Label>Test</Label>
            </StackPanel>
        </DataTemplate>

        <selector:HeaderSelector 
            x:Key="ContentSelector"
            AnyTemplate="{StaticResource Any}"
            NonTemplate="{StaticResource Non}"/>

</UserControl.Resources>

The User control defines a ScrollView. In this ScrollVewi I have placed a ContentPresenter which in turn uses my template selector.

<ScrollViewer VerticalScrollBarVisibility="Auto" >
       <ContentPresenter 
           ContentTemplateSelector="{StaticResource ContentSelector}" 
           DataContext="{Binding ElementName=MyProductFilerView, Path=HasAny}" 
          />

    </ScrollViewer>

The Selector is called. My breakpoint gets hit. but the item parameter of the SelectTemplate method is always null. Therefor i cannot decide which template i should select.

public class  Selector : DataTemplateSelector
    {
        public DataTemplate NonTemplate { get; set; }
        public DataTemplate  AnyTemplate { get; set; }



        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            switch (item)
            {

                default:
                    return base.SelectTemplate(item, container);
            }

        }
    }
  • Could you explain why item is always null in my example?
  • And maybe describe what needs to be done to fill item with a value?
1

There are 1 best solutions below

0
mm8 On

Instead of binding to or set the DataContext property of the ContentPresenter, you should use the Content property:

 <ContentPresenter 
       ContentTemplateSelector="{StaticResource ContentSelector}" 
       Content="{Binding ElementName=MyProductFilerView, Path=HasAny}" />

You could bind Content directly to the DataContext like this:

<ContentPresenter 
       ContentTemplateSelector="{StaticResource ContentSelector}" 
       DataContext="{Binding ElementName=MyProductFilerView, Path=HasAny}"
       Content="{Binding} "/>