Pierre
Pierre

Reputation: 149

WPF ListView binding image from resource, dynamic name

Lets say I have, in my view model a list of persons:

public ObservableCollection<Person> Persons

The Person class is:

public class Person
{
    public string Name{ get; set; }
    public string Photo { get; set; }
}

I would like to display persons in a ListView So far, so good. I have a collection of photo images. My questions are:

  1. Should I add these photos as resources in the project 'Properties->Resources' tab or in a project folder with 'Build Action' set as 'Resource' ?
  2. How can I bind the Person Photo property to the corresponding photo resource (assuming the photo image name is the same as the Person Photo property) ?

Here is my XAML code but of course the binding does not work:

    <ListView Grid.Column="0" Grid.Row="0" ItemsSource="{Binding Persons}" Margin="4">
        <ListView.View>
            <GridView ColumnHeaderToolTip="Persons Information">
                <GridViewColumn DisplayMemberBinding="{Binding Name}" Header="Name"/>
                <GridViewColumn Header="Photo" Width="60">
                    <GridViewColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Photo}"/>
                        </DataTemplate>
                    </GridViewColumn.CellTemplate>
                </GridViewColumn>
            </GridView>
        </ListView.View>
    </ListView>

Thanks in advance.

Upvotes: 0

Views: 1223

Answers (1)

Pierre
Pierre

Reputation: 149

I finally solved my issue by setting the full resource path when creating the Person objects, i.e. : Photo = @"Resources\" + photoName + ".bmp".

Upvotes: 1

Related Questions