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:
- First please create a custom DataTemplateSelector class that inherits from the DataTemplateSelector class.
- Then implement the SelectTemplateCore(Object) method in the custom class and add the condition you used to decide which data template to use.
- 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.