C#: Display Images in GridView/ListView using DataBinding
This article shows how easy it is to display images in ItemsControl element using simple DataBinding. Answer posted to these MSDN questions (1, 2)
Let's take a look at this sample code for the implementation details:
<GridView x:Name="gridView" ItemsSource="{Binding Items}">
<GridView.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Txt}" />
<Image Source="{Binding ImageUri}" Height="60" Width="60"/>
</StackPanel>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
class GridVwItem
{
public Uri ImageUri { get; set; }
public string Txt { get; set; }
}
class GridVwModel
{
public List<GridVwItem> Items { get; set; }
public GridVwModel()
{
//Dummy Data
Items = new List<GridVwItem>();
Items.Add(new GridVwItem() { ImageUri = new Uri("ms-appdata:///local/Logo.png"), Txt="1" });
Items.Add(new GridVwItem() { ImageUri = new Uri("ms-appdata:///local/EnterButton.png"), Txt = "2" });
Items.Add(new GridVwItem() { ImageUri = new Uri("ms-appdata:///local/SplashScreen.png"), Txt = "3" });
}
}
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.DataContext = new GridVwModel();
}
}