Search code examples
c#wpfmvvmbindingdatagrid

Display an image in a DataGrid-Column


I'm trying to display an image in a DataGrid-Column next to other data. My model looks like this:

public class Person 
{
    public string Name { get; set; }
    public string Address { get; set; }
    public Bitmap Image { get; set; }
}

The ViewModel:

public ObservableCollection<Person> Persons
    {
        get
        {
           return this.persons;
        }

        set
        {
            this.persons = value;
        }
    }

And my DataGrid is this:

<DataGrid Name="Persons"
              Grid.Row="1"
              Grid.Column="0"
              Margin="10"
              AutoGenerateColumns="False"
              IsReadOnly="True"
              ItemsSource="{Binding Path=Persons}">
        <DataGrid.Columns>
            <DataGridTemplateColumn Width="80">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <Image Source="{Binding}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
            <DataGridTextColumn Width="120"
                                Binding="{Binding Path=Name}"
                                Header="Name" />
            <DataGridTextColumn Width="120"
                                Binding="{Binding Path=Address}"
                                Header="Address" />
        </DataGrid.Columns>
    </DataGrid>

The Name and Adress get displayed correctly, but the image is empty... Do you know what I'm doing wrong?

Thanks in advance and have a nice day


Solution

  • If your Image is of a System.Drawing.Bitmap you should change it to System.Windows.Media.Imaging.BitmapImage and then change also Image.Source binding which at the moment binds to whole Person object to its Image property

    <Image Source="{Binding Image}" />