以下是一些示例代码,可以更好地说明我在这里要完成的工作。 基本上我需要设置只能从UI线程设置的属性。有什么想法吗?
public ref class ExtendedImage : public System::Windows::Controls::Image
{
public:
void SetImageFromUrl (System::String^ url)
{
if (!System::Uri::TryCreate (path, System::UriKind::Absolute, this->m_uri) || this->m_uri->IsFile)
return;
System::Threading::Thread^ downloadImage = gcnew System::Threading::Thread (gcnew System::Threading::ThreadStart (this, &ExtendedImage::DownloadAndSetImage));
downloadImage->Start ();
}
private:
System::Uri^ m_uri;
void DownloadAndSetImage ()
{
System::Windows::Media::Imaging::BitmapImage^ bitmap = gcnew System::Windows::Media::Imaging::BitmapImage (this->m_uri);
//execute this->Source = bitmap; on UI thread
}
}
更新:
将问题代码组合到正确答案C#解决方案后的一些有用信息。要获取UI线程Dispatcher,请使用System::Windows::Application::Current->Dispatcher
。
答案 0 :(得分:3)
WPF已经异步执行从URI创建BitmapImage,因此无需启动另一个线程。
这样做:
using namespace System;
using namespace System::Windows::Controls;
using namespace System::Windows::Media::Imaging;
public ref class ExtendedImage : public Image
{
public:
void SetImageFromUrl(System::String^ url)
{
Uri^ uri;
if (Uri::TryCreate(url, UriKind::Absolute, uri) && !uri->IsFile)
{
Source = gcnew BitmapImage(uri);
}
}
};
无论如何,如果您确实需要从URI手动下载图像缓冲区并在单独的线程中从该缓冲区创建BitmapImage,您可以按照this answer中显示的方法来处理类似的问题。