Luc Wanlin
Luc Wanlin

Reputation: 105

WPF ListView-GridView : bind image

I'm working on a desktop WPF app (.net 4). One of its window contains a tabControl whose tabitems contain each aListview, whose view is a GridView. TabItems, ListViews and GridViews are all dynamically generated. When the user hits a button on each tabitem, the ListView view is updated with a DataTable defaultview from SQL Server (of course, the selected rows depend on user's request, but that's irrelevant here).

Everything is working just fine, with the (shortened) code below for the GridView (gv) generated dynamically :

foreach (KeyValuePair<string, string> Column in Columns)
{
    GridViewColumn gvc = new GridViewColumn();
    gvc.DisplayMemberBinding = new Binding(Column.Key);
    gv.Columns.Add(gvc);
}

As you can see, I created a Dictionary with column names matching the columns of the DataTable received from SQL Server (I use the Column.Value for special use, also irrelevant here).

My question is "simple" :

One of the column contains a value which I would like to show as a logo ; plainly, the SQL server column contains strings (let's say, "a" or "b") and I have images named "a.png" and "b.png" (which I can display dynamically, like testimage.Source = new BitmapImage(new Uri("../../images/a.png", UriKind.Relative))).

So, how could I, in c#, replace the "a" and "b" letters in my ListView column by "a.png" and "b.png" ?

I hope I'm clear and already thank every people who will take on their time to read and try to answer my question.

Upvotes: 1

Views: 2721

Answers (1)

Edward
Edward

Reputation: 8596

You can use a Data Binding ValueConverter for this

Your converter class -

    public class MyImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string imageName = (string) value;
            return new BitmapImage(new Uri("../../images/" + imageName + ".png", UriKind.Relative));
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

In your code-behind

foreach (KeyValuePair<string, string> Column in Columns)
{
    GridViewColumn gvc = new GridViewColumn();
    Binding binding = new Binding(Column.Key);
    if (Column.Key == "Image")
    {
        binding.Converter = new MyImageConverter();
    }
    gvc.DisplayMemberBinding = binding;
    gv.Columns.Add(gvc);
}

Upvotes: 1

Related Questions