繁体   English   中英

赢得8个Metro应用程序C#多个itemTemplate

[英]win 8 metro app c# multiple itemTemplate

我正在开发Metro应用,但遇到了情况。 在我的其中一个页面中,我将listview与一个自定义项目模板一起使用,该模板显示图像及其名称。 现在,如果图像是垂直的,我必须使用2项模板。我必须使用另一个具有更高高度的模板。 listview中可以有2个不同的模板吗? 我必须在.cs中更改模板,例如, if the image is horizontal listview.ItemTemplate = 1 else if the image is vertical listvew.ItemTemplate =2 ,我该如何使用它?

首先创建一个自定义DataTemplateSelector类:

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 -确保在模板选择器内的正确位置搜索它们):

<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级别,即页面或应用程序级别):

<ListView.Resources>
    <local:OrientationTemplateSelector x:Key="OrientationTemplateSelector" />
</ListView.Resources>

现在,您可以将其设置为ListView ItemTemplateSelector

<ListView ItemTemplateSelector="{StaticResource OrientationTemplateSelector}" ItemsSource="{Binding CustomItemsList}" />

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM