How to change listview template

hedoa 41 Reputation points

How to change listview template based on the content? We need to adjust the template without using many listview.

Universal Windows Platform (UWP)
No comments
{count} votes

Accepted answer
  1. Roy Li - MSFT 28,051 Reputation points Microsoft Vendor


    Welcome to Microsoft Q&A!

    So your question is how to use different DataTemplate in one ListView, right?

    To achieve this, I'd suggest you use the DataTemplateSelector Class. It is used to select different DataTemplates for the ListView based on certain conditions.

    First of all, you will need to create two or more DataTemplates according to your scenario. Then you need to create a subclass of DataTemplateSelector (a class that derives from it) in your code-behind. In your class, you declare each template as a property of the class. Then, you override the SelectTemplateCore method to include your own template selection logic.

    Due to a known issue, I won't show the XAML code here. I'll show some code behind here and you could refer to the full sample here:

     public sealed partial class MainPage : Page  
            public List sources { get; set; }  
            public MainPage()  
                sources = new List();  
                this.DataContext = this;  
        public class MyDataTemplateSelector : DataTemplateSelector  
            //this is the templates defined in the xaml  
            public DataTemplate FirstTemplate { get; set; }  
            public DataTemplate SecondTemplate { get; set; }  
            protected override DataTemplate SelectTemplateCore(object item)  
                string str = item as string;  
                if (str.Equals("1"))  
                    return FirstTemplate;  
                if (str.Equals("2"))  
                    return SecondTemplate;  
                return base.SelectTemplateCore(item);  
            protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)  
                return SelectTemplateCore(item);  

    Also, you could find more information from this official document:

0 additional answers

Sort by: Most helpful