How to display Bitmap Image in image control on WPF using C#

感情迁移 提交于 2019-12-11 00:35:41

问题


I want that when I double click on a row in ListView, it should display the Image corresponding to that row. This row also contains the path of the Image.

I tried the following but it displays the same Image for all rows because I have given the path for a specific Image:

private void ListViewEmployeeDetails_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
    ImageSource imageSource = new BitmapImage(new Uri(@"C:\northwindimages\king.bmp"));
    image1.Source = imageSource;
}

Please suggest something.


回答1:


They key is to retrieve the row index that was clicked, and get the image URL for that row. Since you say you are clicking on the row, this can be done in a method similar to that below

private void ListViewEmployeeDetails_MouseDoubleClick(object sender, MouseButtonEventArgs e) 
    {
        DataRow row = (DataRow)sender; //Get the row that was clicked
        string imageURL = row["imageUrl"].ToString();//Get the img URL for that row
        ImageSource imageSource = new BitmapImage(new Uri(imageURL));
        image1.Source = imageSource; 
    }

Hope this helps




回答2:


Suppose that:

  1. The list you are binding to contains Elephant objects and,
  2. You want the image to show Elephant.Picture whenever you double-click an item.

You can set the image from an event handler as follows:

private void ListViewEmployeeDetails_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
  var viewItem = sender as ListViewItem;
  if(viewItem!=null)
  {
    var elephant = viewItem.DataContext as Elephant;
    image1.Source = elephant.Picture;
  }
}

Note that it is important to only accept double clicks on the ListViewItem.

The above code assumes that elephant.Picture is of type ImageSource. If it is something else you will have to convert it. For example, if instead Elephant has a string "PicturePath" property, the image1.Source line would change to:

    image1.Source = new BitmapImage(new Uri(elephant.PicturePath));


来源:https://stackoverflow.com/questions/1949779/how-to-display-bitmap-image-in-image-control-on-wpf-using-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!