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

Fei Xue - MSFT 1,111 Reputation points
2019-10-30T06:35:18.337+00:00

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?

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

Accepted answer
  1. Roy Li - MSFT 33,371 Reputation points Microsoft Vendor
    2019-10-31T01:41:59.84+00:00

    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.

    3 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.