将图像插入到 FlowDocument
Inserting Image to FlowDocument
我正在开发一个 wpf 应用程序。我想创建一个 FlowDocument 对象并打印它。由于创建步骤需要几秒钟并冻结 UI,我将代码移至新线程。问题是我需要在 FlowDocument 中设置一个 Image 并且需要创建 Image UIElement,但是 UI 控件不能在后台线程中创建!
我也尝试了很多 Dispather.Invoke() 场景,但它们捕获了关于对象所有者线程的异常。
不知道有没有其他方法可以在FlowDocument中插入图片?或者是否可以在后台线程中创建图像 UI 元素?
如有任何建议,我们将不胜感激。
P.S:一些示例代码=>
BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
Image v = new Image() { Source = bitmapImage };
currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));
Image v = ((App)Application.Current).Dispatcher.Invoke(new Func<Image>(() =>
{
BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
return new Image() { Source = bitmapImage};
}));
currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));
如果您不需要修改BitmapImage,那么您可以将其冻结并在UI线程上使用。
// Executing on non UI Thread
BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
bitmapImage.Freeze(); // Has to be done on same thread it was created on - maybe freeze it in the Singleton instead?
Application.Current.Dispatcher.Invoke(() => {
// Executing on UI Thread
Image v = new Image() { Source = bitmapImage };
currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));
});
与您交谈后,您真正需要做的是 运行 您在 STA 线程中的任务,因为您要对其进行 UI 控制。
怎么做?看到这个答案:
Set ApartmentState on a Task
我正在开发一个 wpf 应用程序。我想创建一个 FlowDocument 对象并打印它。由于创建步骤需要几秒钟并冻结 UI,我将代码移至新线程。问题是我需要在 FlowDocument 中设置一个 Image 并且需要创建 Image UIElement,但是 UI 控件不能在后台线程中创建! 我也尝试了很多 Dispather.Invoke() 场景,但它们捕获了关于对象所有者线程的异常。
不知道有没有其他方法可以在FlowDocument中插入图片?或者是否可以在后台线程中创建图像 UI 元素?
如有任何建议,我们将不胜感激。
P.S:一些示例代码=>
BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
Image v = new Image() { Source = bitmapImage };
currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));
Image v = ((App)Application.Current).Dispatcher.Invoke(new Func<Image>(() =>
{
BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
return new Image() { Source = bitmapImage};
}));
currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));
如果您不需要修改BitmapImage,那么您可以将其冻结并在UI线程上使用。
// Executing on non UI Thread
BitmapImage bitmapImage = SingletonSetting.GetInstance().Logo;
bitmapImage.Freeze(); // Has to be done on same thread it was created on - maybe freeze it in the Singleton instead?
Application.Current.Dispatcher.Invoke(() => {
// Executing on UI Thread
Image v = new Image() { Source = bitmapImage };
currnetrow.Cells.Add(new TableCell(new BlockUIContainer(v)));
});
与您交谈后,您真正需要做的是 运行 您在 STA 线程中的任务,因为您要对其进行 UI 控制。 怎么做?看到这个答案:
Set ApartmentState on a Task