1

在Windows Metro應用程序(發佈預覽版)中,我從數據點動態創建圖像並使用數據綁定來顯示圖像。如何最好地創建一個將返回動態構建的ImageSource的屬性?

由於圖像創作過程繁重,我希望在任務中完成。 所以我的財產,目前編碼是這樣的:

public ImageSource Diagram 
{ 
    get 
    { 
     if (this.diagram == null) 
     { 
      DiagramGenerator.GetDiagram(this.DataPoints, this.Width, this.Height).ContinueWith((t) => 
      { 
       this.Diagram = t.Result; 
      } 
     } 
     return this.diagram; 
    } 
    set 
    { 
     this.SetProperty(ref this.diagram, value); 
    } 
} 

而且DiagramGenerator樣子:

public static async Task<ImageSource> DiagramGenerator.GetDiagram(List<DataPoint> dataPoints, int width, int height) 
{ 
    WriteableBitmap bmp = BitmapFactory.New(width, height); 

    // Build the image... 

    return bmp; 
} 

在XAML中,我結合是非常簡單的

<Image Source="{Binding Diagram}" Stretch="UniformToFill"/> 

不幸的是,使用的代碼以上不起作用。

我得到OnPropertyChanged方法中引發的異常(例如,在this.Diagram = t.Result上面):「該應用程序調用一個接口,被編組爲一個不同的線程。」

我然後使用試圖馬歇爾到UI線程:

Window.Current.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Norma,()=> {this.Diagram = t.Result; });

但是,這不工作,因爲Window.Current爲空!

如何解決這個問題?

非常感謝您的建議。

回答

0

當您在UI線程中並將其存儲以供稍後使用時,您可以抓取Window.Current.Dispatcher,比如說創建Diagram對象時。或者,分派器存儲在DependencyObject中,以便您可以將其從外部抓取(即它在任何UIElement對象中)。