c# – 如何在不创建List的情况下将图像源绑定到路径列表?
发布时间:2020-12-15 20:54:21 所属栏目:百科 来源:网络整理
导读:我想创建一个ListView,其中包含描述和几个图像(作为标记). 例如: item1 USA image1 image2 image3item2 Canada image2 image3 image4item3 France image1 image3 image4 由于这些图像只是标签,因此可以重复它们. 这个ListView的xaml是 ListView x:Name="MyL
我想创建一个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> (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |