2016-09-02 116 views
0

我正在使用wpf應用程序。我想創建一個FlowDocument對象並打印它。由於創建步驟需要幾秒鐘並凍結UI,因此我將代碼移至新線程。問題是我需要在FlowDocument中設置一個Image並需要創建Image UIElement,但不能在後臺線程中創建UI Controls! 我也嘗試了很多Dispather.Invoke()方案,但它們捕獲有關對象所有者線程的異常。將圖像插入到FlowDocument

我不知道是否有任何其他方法將圖像插入FlowDocument?或者是否有可能在後臺線程中創建圖像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))); 

回答

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

+0

感謝您的回答,但它導致在最後一行異常。它說「調用線程不能訪問這個對象,因爲不同的線程擁有它」 – Evil

+0

currnetrow.Cells ...線? currnetrow做了什麼線程? –

+0

是的,後臺線程創建它!我想在UI線程中使用currentrow是個問題! – Evil