BitmapImage数据绑定单例
本文关键字:单例 数据绑定 BitmapImage | 更新日期: 2023-09-27 18:16:04
我有一个单例BitmapImage我试图将它绑定到我的xaml视图,我得到:
The calling thread cannot access this object because it is owned by another thread
下面是我的代码:
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.UriSource = new Uri(fullFilePath, UriKind.Absolute);
bitmap.EndInit();
MySingleton.Instance.image = bitmap;
My singleton:
private BitmapImage _image;
public BitmapImage image
{
get { return _image; }
set
{
_image = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(image)));
}
}
And my xaml:
<Image Source="{Binding image, Source={x:Static module:MySingleton.Instance}}" Name="TestImage" HorizontalAlignment="Center" Height="Auto" VerticalAlignment="Center" Width="Auto"></Image>
我尝试bitmap.Freeze();
,但得到错误:
freeable不能被冻结
我不知道它是否没有意义,但我在websocket onmessage事件中实例化了位图
您的代码必须放在Dispatcher中。
Application.Current.Dispatcher.Invoke(() =>
{
//(your code here)
});
或
Application.Current.Dispatcher.BeginInvoke((Action)(() =>
{
//(your code here)
}));