I want to create a ListView which contains a description and several images(as tags).
For example:
item1 USA image1 image2 image3
item2 Canada image2 image3 image4
item3 France image1 image3 image4
Since those images are simply tags, they may be repeated.
The xaml of this ListView is
<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>
And the C# code of the class for binding:
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# code of main program:
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;
}
In this example, image3 appears in three countries, so the path of it should be stored in three different list. However, all these paths are the same, "Assets/Image3" !
I think to store all the paths in each list of individual country wastes a lot of space, because all the image path are repeated. Is it necessary for the image source to bind with a list? Or are there any other methods for the image source to bind with little amount of source data but high frequency of repeating?
As you are using a DataTemplate within GridView, you can use TemplateSelector as an alternate approach. Write different DataTemplates in Xaml with source as needed and then use contentPresenter to add that Template to your ListView DataTemplate at runtime.
<DataTemplate>
<ContentPresenter
ContentTemplateSelector="{StaticResource ResourceKey=myImageTemplateSelector}">
</ContentPresenter>
</DataTemplate>