Im new in WPF MVVM and i have a problem with binding a new BitmapImage
to Image.Source
control.
Binding image from filepath is pretty easy, but how bind new Bitmap
or BitmapImage
to Image
label in WPF?
My scenerio:
I have an method to do something with image (it is hide in Model
folder in Class
for methods for working on images:
static public BitmapImage Init(Bitmap bmp)
{
//Do stuff
return BitmapConversion.Bitmap2BitmapImage(newImage);
//BitmapConversion is my own class for converting images
}
In this section, i made what i want to do with my Bitmap and return BitmapImage
.
In ViewModel , i have this, opening an image and Init function that i want to:
namespace Test.ViewModels
{
class ViewModel
{
public string filepath { get; set; }
public ViewModel()
{
OpenFileDialog openPicture = new OpenFileDialog();
openPicture.Filter = "Image files|*.bmp;*.jpg;*.gif;*.png;*.tif|All files|*.*";
openPicture.FilterIndex = 1;
if (openPicture.ShowDialog() == true)
{
filepath = openPicture.FileName;
Model.Init(new Bitmap(filepath)); //init function from above
}
}
public string DisplayedImage
{
get { return filepath; }
}
}
My View looks like:
<!-- row1 -->
<Image Source="{Binding DisplayedImage}" />
<!-- row2 -->
<Image Source ={Binding ?}" />
My question is, how to bind properly object like BitmapImage to source of Image label?
Thanks for any advices
This should work with ImageSource instead of string:
public ImageSource DisplayedImage
{
get { return new BitmapImage(new Uri(filepath)); }
}
Or with your ViewModel:
class ViewModel
{
public ViewModel()
{
...
if (openPicture.ShowDialog() == true)
{
DisplayedImage = Model.Init(new Bitmap(openPicture.FileName));
}
}
public ImageSource DisplayedImage { get; private set; }
}
You should however consider to replace your Model.Init
method with one that operates on a WPF BitmapSource instead of a WinForms Bitmap.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.