微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 如何在不创建List的情况下将图像源绑定到路径列表?

我想创建一个ListView,其中包含描述和几个图像(作为标记).

例如:

item1 USA image1 image2 image3

item2 Canada image2 image3 image4

item3 France image1 image3 image4

由于这些图像只是标签,因此可以重复它们.

这个ListView的xaml是

<ListView x:Name="MyList">
        <ListView.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock x:Name="Coutry" Text="{Binding CountryName}"/>
                    <GridView>
                        <GridView.ItemTemplate>
                            <DataTemplate>
                                <Image x:Name="CountryTags" Source="{Binding CountryProperty}"/>
                            </DataTemplate>
                        </GridView.ItemTemplate>
                    </GridView>
                </StackPanel>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

和绑定类的C#代码

public class Country
{
    public string CountryName { get; set; }
    // this list store image path for tags required for each country
    public List<string> CountryProperty { get; set; }

    public Country(string CountryName,List<string> CountryProperty)
    {
        this.CountryName = CountryName;
        this.CountryProperty = CountryProperty;
    }    
}

主程序的C#代码

protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        this.navigationHelper.OnNavigatedTo(e);

        List<Country> Countries = new List<Country>();
        List<string> ImgPath = new List<string>();

        // first country
        ImgPath.Add("Assets/Image1");
        ImgPath.Add("Assets/Image2");
        ImgPath.Add("Assets/Image3");
        Countries.Add(new Country("USA",ImgPath));

        // second country
        ImgPath.Add("Assets/Image2");
        ImgPath.Add("Assets/Image3");
        ImgPath.Add("Assets/Image4");
        Countries.Add(new Country("Canada",ImgPath));

        // third country
        ImgPath.Add("Assets/Image1");
        ImgPath.Add("Assets/Image3");
        ImgPath.Add("Assets/Image4");
        Countries.Add(new Country("France",ImgPath));

        // bind data
        MyList.ItemsSource = Countries;
    }

在此示例中,image3出现在三个国家/地区,因此它的路径应存储在三个不同的列表中.但是,所有这些路径都是相同的,“Assets / Image3”!

我认为将每个列表中的所有路径存储在各个国家/地区的废弃物中需要很多空间,因为所有的图像路径都会重复出现.图像源是否有必要与列表绑定?或者是否有任何其他方法使图像源与少量的源数据绑定但重复频率高?

解决方法

在GridView中使用DataTemplate时,可以使用TemplateSelector作为替代方法.根据需要使用source在Xaml中编写不同的DataTemplates,然后使用contentPresenter在运行时将该模板添加到ListView DataTemplate.

<DataTemplate>       
          <ContentPresenter 
              ContentTemplateSelector="{StaticResource ResourceKey=myImageTemplateSelector}">
          </ContentPresenter>

</DataTemplate>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐