question

FeiXue-MSFT avatar image
0 Votes"
FeiXue-MSFT asked ·

Switch the ListView Datatemplate from one data template to another data template?

I am developing Universal Windows 10 app, in one of my current project I want to change the ListView Data Template in runtime.

Right now I have used only one Data Template, but in my scenario after a button is pressed, I want to change it to another data template.

How to write the code for this problem?

windows-uwpwindows-uwp-xamlwindows-uwp-runtime
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
3 Votes"
RoyLi-MSFT answered ·

Hello,

Welcome to our Microsoft Q&A platform!

Using a DataTemplateSelector, we can determine at runtime which DataTemplate to apply to show items in a control for the GridView & ListView.
For how to implement it, please check the following steps:

  1. First please create a custom DataTemplateSelector class that inherits from the DataTemplateSelector class.

  2. Then implement the SelectTemplateCore(Object) method in the custom class and add the condition you used to decide which data template to use.

  3. Create two Data Templates in Xaml and assign them to the data templates which defined in the custom DataTemplateSelector class.

Here is a simple demo:

Xaml code:


Code Behind:

 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
     {
         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);
         }
 }


Thanks.


· 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.