赢8地铁应用C#多的ItemTemplate [英] win 8 metro app c# multiple itemTemplate
问题描述
我工作的一个地铁应用程序,我的情况。
在我的网页之一,我用列表视图与显示图像,它的名字自定义项目模板。
现在我必须使用2项模板,如果图像是垂直我必须使用另一个模板较长的高度。能有邻列表视图2个不同的模板?
我必须更改模板的.cs像
如果图像是水平listview.ItemTemplate = 1
,否则如果图像是垂直listvew.ItemTemplate = 2
我如何使用它?
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?
推荐答案
首先创建一个自定义的 DataTemplateSelector
类:
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;
}
}
定义您的项目模板,资源(在我的情况在的App.xaml
- 确保你的模板里面选择合适的地方寻找他们):
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>
添加模板选择的资源,以及(在的ListView
级别,如下或任何更高,即页面或应用程序级):
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>
现在你可以将其设置为的 ItemTemplateSelector
您的的ListView
:
Now you can set it as ItemTemplateSelector
to your ListView
:
<ListView ItemTemplateSelector="{StaticResource OrientationTemplateSelector}" ItemsSource="{Binding CustomItemsList}" />
这篇关于赢8地铁应用C#多的ItemTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!