如何将位图图像添加到wpf ListView中

时间:2011-09-21 05:13:01

标签: c# .net wpf listview .net-3.5

这就是我所拥有的

<GridViewColumn Header="Status" >
    <GridViewColumn.CellTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="{Binding Image}" Width="22" Height="22"/>
            </StackPanel>
        </DataTemplate>
    </GridViewColumn.CellTemplate>
</GridViewColumn>

Image是一个System.Drawing.Bitmap图像,我从Namespace.Resources获取。

无论我尝试什么,我都无法在列中显示任何图像。

1 个答案:

答案 0 :(得分:3)

您需要将System.Drawing.Bitmap转换为ImageSource,这是WPF用于图像的内容。您可以通过Imaging.CreateBitmapSourceFromHBitmap

执行此操作
// Include, in your class or elsewhere:
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
private static extern bool DeleteObject(IntPtr hObject);

Bitmap image = LoadYourBitmap();

IntPtr hbitmap = image.GetHbitmap();
try
{
   var bitmapSource = Imaging.CreateBitmapSourceFromHBitmap(
      hbitmap, IntPtr.Zero, Int32Rect.Empty,
      Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
    // Clean up the bitmap data
    DeleteObject(hbitmap);
}