【发布时间】:2016-11-03 14:55:18
【问题描述】:
我有一个单例 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;
我的单身:
private BitmapImage _image;
public BitmapImage image
{
get { return _image; }
set
{
_image = value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(image)));
}
}
还有我的 xaml:
<Image Source="{Binding image, Source={x:Static module:MySingleton.Instance}}" Name="TestImage" HorizontalAlignment="Center" Height="Auto" VerticalAlignment="Center" Width="Auto"></Image>
我尝试了bitmap.Freeze();,但得到了错误:
Freezable 不能被冻结
我不知道这是否毫无意义,但我在 websocket onmessage 事件中实例化了位图。
【问题讨论】:
-
fullFilePath是本地文件路径吗? -
@Clemens 没有 url,我在没有绑定的情况下测试了代码,并使用 Lupu Silviu 给出的“Application.Current.Dispatcher.Invoke(()”,它正在工作,但我还没有找到为什么绑定不起作用。
-
你不能冻结图像可能是因为它的缓存选项是
Default。尝试在调用EndInit()之前将位图的CacheOption设置为BitmapCacheOption.OnLoad。 -
@dymanoid 这不再是重点,但我尝试了它,因为它可能是一个很酷的信息,但不是我在调用 Freeze 时仍然收到错误
-
@dymanoid 您不能在下载图像数据时冻结 BitmapImage。您可以检查其
IsDownloading属性并为其DownloadCompleted事件附加一个处理程序。下载完成后,您可以调用 Freeze()。
标签: c# wpf xaml data-binding singleton