将图像插入FlowDocument

问题描述 投票:0回答:1

我正在研究一个wpf应用程序。我想创建一个FlowDocument对象并打印它。由于创建步骤需要几秒钟并冻结UI,因此我将代码移动到新线程。问题是我需要在FlowDocument中设置一个Image并需要创建Image UIElement,但是无法在后台线程中创建UI控件!我也尝试了很多Dispather.Invoke()方案,但它们捕获了有关对象所有者线程的异常。

我想知道是否还有其他方法可以将图像插入FlowDocument?或者是否可以在后台线程中创建Image UIElement?

任何建议将不胜感激。

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)));
c# wpf multithreading flowdocument
1个回答
1
投票

如果您不需要修改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

© www.soinside.com 2019 - 2024. All rights reserved.