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 template if image is vertical I have to use another template with longer height. can there be 2 different templates in o listview ?
I must change the template in .cs something like
if the image is horizontal listview.ItemTemplate = 1
else if the image is vertical listvew.ItemTemplate =2
how Can I use this?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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}" />