控件仅显示第一个图像,如果属性发生更改(并且事件被触发),控件甚至不会尝试再次获取该值。 如果窗口初始化时属性为null,那么如果稍后对图像进行了修改,则也不会显示任何内容。 图像大约是2MB位图
这是XAML
<Image
Grid.Row="1"
Grid.Column="0"
Grid.ColumnSpan="2"
Source="{Binding Path=CurrentImg,UpdateSourceTrigger=PropertyChanged, Mode= TwoWay}"/>
这是在视图模型中:
private BitmapImage _CurrentImg;
public BitmapImage CurrentImg
{
get { return _CurrentImg; }
set
{
_CurrentImg = value;
RaisePropertyChanged("CurrentImg");
}
}
public void ButtonCommandExecute()
{
TestAlgo.Next();
this.CurrentImg = TestAlgo.toWpfBitmapImage();
}
最后,这是从System.Drawing.Bitmap
创建BitmapImage的方法 public BitmapImage toWpfBitmapImage()
{ return convertBitmapToBitmapSource(this.CurBitmap); }
/// <summary>
/// Converts a <see cref="System.Drawing.Bitmap"/> to <see cref="System.Windows.Media.Imaging.BitmapSource"/>
/// </summary>
/// <param name="bitmap">Source</param>
/// <returns>Converted image</returns>
public static BitmapImage convertBitmapToBitmapSource(System.Drawing.Bitmap bitmap)
{
//salvo la bitmap nel MemoryStream, in modo che lo posso usare come sorgente per una nuova BitmapSource
BitmapImage imageToReturn = new BitmapImage();
using (MemoryStream stream = new MemoryStream())
{
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
//creo la nuova BitmapSource da ritornare
stream.Seek(0, SeekOrigin.Begin);
imageToReturn.BeginInit();
imageToReturn.CacheOption = BitmapCacheOption.OnLoad;
imageToReturn.CreateOptions = BitmapCreateOptions.PreservePixelFormat;
imageToReturn.StreamSource = stream;
imageToReturn.EndInit();
}
return imageToReturn;
}
这是实例化主窗口的地方,视图模型作为参数传递并在构造函数中设置。
public partial class App : Application
{
MainWindowVM MainWinVM;
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWinVM = new MainWindowVM();
MainWindow win = new MainWindow(MainWinVM);
win.Show();
}
protected override void OnExit(ExitEventArgs e)
{
MainWinVM.SaveDb();
base.OnExit(e);
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
this.DataContext = new MainWindowVM();
InitializeComponent();
}
public MainWindow(MainWindowVM vm)
{
DataContext = vm;
InitializeComponent();
}
}
答案 0 :(得分:1)
您是否实施了INotifyPropertyChanged接口???
设置值后,请在CurrentImg的setter上使用sendPropertyChanged(“CurrentImg”)。
private BitmapImage currentImg;
public BitmapImage CurrentImg
{
get { return currentImg; }
set
{
currentImg = value;
SendPropertyChanged("CurrentImg");
}
}
请参阅以下链接。
http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged(v=vs.110).aspx