How to apply Different Data template for each group in ListView

302 Views Asked by At

Is there anyway to apply different data template for each group in listview , I can able to do HeaderTemplateSelector but how to do GroupTemplateSelector .

Below code i done for HeaderTemplateSelector for group

<DataTemplate x:Key="Template1">
    <StackPanel Margin="0.5">
        <TextBlock Text="{Binding Path=Key}" />
    </StackPanel>
</DataTemplate>
<DataTemplate x:Key="Template2">
    <StackPanel Margin="10">
        <TextBlock Text="{Binding Path=Key}" />
    </StackPanel>
</DataTemplate>

<ListView.GroupStyle>
    <GroupStyle>
        <GroupStyle.HeaderTemplateSelector>
            <local:GroupTemplateSelector Template1="{StaticResource Template1}"
                                         Template2="{StaticResource Template2}" />
        </GroupStyle.HeaderTemplateSelector>
    </GroupStyle>
</ListView.GroupStyle>

C#

public class GroupTemplateSelector : DataTemplateSelector
{
    public DataTemplate Template1 { get; set; }
    public DataTemplate Template2 { get; set; }

    protected override DataTemplate SelectTemplateCore(
        object item, 
        DependencyObject container)
    {
        if (item != null)
        {
            var group = item as IGrouping<string, MyClass>;
            switch (group.Key)
            {
                case "No":
                    return Template1;
                case "Yes":
                    return Template2;
            }
        }

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

How to do different selector for Group content?

1

There are 1 best solutions below

0
On

You could just implement a ListView.ItemTemplateSelector and in its SelectTemplateCore take the MyClass instance and check which group does it belong to and select the template accordingly. To get the best performance, it would be best if MyClass had a quick way (e.g. a property) by which you could tell the group.