【问题标题】:Wpf - BitmapImage data binding SingletonWpf - BitmapImage 数据绑定 Singleton
【发布时间】: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


【解决方案1】:

您的代码必须放在 Dispatcher 中。

Application.Current.Dispatcher.Invoke(() =>
{
  //(your code here)
});

Application.Current.Dispatcher.BeginInvoke((Action)(() =>
{
   //(your code here)
}));

【讨论】:

  • 谢谢!我已经看到了,但是我选择了错误的导入:S。代码现在可以工作,但图像仍然不显示,图像显示在没有数据绑定的原始代码中。
  • 好吧,绑定工作正常,我的测试失败了。
猜你喜欢
  • 2019-01-24
  • 1970-01-01
  • 2015-06-26
  • 2013-12-07
  • 2017-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-30
相关资源
最近更新 更多