I working on a metro app and I have situation. In one of my pages I used listview with a custom item template which displays an image and its name. now I have to use 2 item
First create a custom DataTemplateSelector class:
public class OrientationTemplateSelector : DataTemplateSelector
{
protected override DataTemplate SelectTemplateCore(object item, DependencyObject container)
{
// cast item to your custom item class
var customItem = item as CustomItem;
if (customItem == null)
return null;
string templateName = String.Empty;
if (customItem.Width > customItem.Height
{
// image is horizontal
templateName = "HorizontalItemTemplate";
}
else
{
templateName = "VerticalItemTemplate";
}
object template = null;
// find template in App.xaml
Application.Current.Resources.TryGetValue(templateName, out template);
return template as DataTemplate;
}
}
Define your item templates as resources (in my case in App.xaml
- make sure you search for them in the right place inside template selector):
<Application.Resources>
<DataTemplate x:Key="HorizontalItemTemplate">
<!-- item template for horizontal image -->
</DataTemplate>
<DataTemplate x:Key="VerticalItemTemplate">
<!-- item template for vertical image -->
</DataTemplate>
</Application.Resources>
Add the template selector as resource as well (at the ListView
level as below or anywhere higher, i.e. page or application level):
<ListView.Resources>
<local:OrientationTemplateSelector x:Key="OrientationTemplateSelector" />
</ListView.Resources>
Now you can set it as ItemTemplateSelector to your ListView
:
<ListView ItemTemplateSelector="{StaticResource OrientationTemplateSelector}" ItemsSource="{Binding CustomItemsList}" />