[英]C#, binding new BitmapImage, WPF MVVM
我是 WPF MVVM 的新手,我在將新的BitmapImage
綁定到Image.Source
控件時Image.Source
了問題。
從文件路徑綁定圖像非常簡單,但是如何將新的Bitmap
或BitmapImage
綁定到 WPF 中的Image
標簽?
我的場景:
我有一種處理圖像的方法(它隱藏在Class
Model
文件夾中,用於處理圖像的方法:
static public BitmapImage Init(Bitmap bmp)
{
//Do stuff
return BitmapConversion.Bitmap2BitmapImage(newImage);
//BitmapConversion is my own class for converting images
}
在本節中,我用我的 Bitmap 做了我想做的事情並返回BitmapImage
。
在ViewModel 中,我有這個,打開我想要的圖像和 Init 函數:
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; }
}
}
我的視圖看起來像:
<!-- row1 -->
<Image Source="{Binding DisplayedImage}" />
<!-- row2 -->
<Image Source ={Binding ?}" />
我的問題是,如何將 BitmapImage 等對象正確綁定到 Image 標簽的源?
感謝您的任何建議
這應該適用於 ImageSource 而不是字符串:
public ImageSource DisplayedImage
{
get { return new BitmapImage(new Uri(filepath)); }
}
或者使用您的 ViewModel:
class ViewModel
{
public ViewModel()
{
...
if (openPicture.ShowDialog() == true)
{
DisplayedImage = Model.Init(new Bitmap(openPicture.FileName));
}
}
public ImageSource DisplayedImage { get; private set; }
}
但是,您應該考慮將Model.Init
方法替換為在 WPF BitmapSource 而不是 WinForms Bitmap 上運行的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.