question

hedoa-3453 avatar image
0 Votes"
hedoa-3453 asked ·

How to change listview template

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

windows-uwp
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

RoyLi-MSFT avatar image
0 Votes"
RoyLi-MSFT answered ·

Hello,

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: https://github.com/RoyLi-MSFT/ListViewTemplate

  public sealed partial class MainPage : Page
     {
         public List sources { get; set; }
         public MainPage()
         {
             this.InitializeComponent();
             sources = new List();
             sources.Add("1");
             sources.Add("2");
             sources.Add("1");
             sources.Add("2");
             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: https://docs.microsoft.com/en-us/windows/uwp/design/controls-and-patterns/data-template-selector





· Share
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.