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

Fei Xue - MSFT 1,111 Reputation points

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?

Locked Question. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments

Answer accepted by question author

Anonymous

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.

0 comments No comments

1 additional answer

  1. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more