2013-03-25 51 views
2

在我的xaml文件中,我有一個名爲OutputImg的圖像。 我還有一個名爲OutputTB的文本塊,用於顯示圖像的名稱和一個按鈕,讓我從我的圖片文件夾中選擇圖像。背後在項目之外添加圖像C#Windows Store應用程序

代碼:

private async void Button_Click_1(object sender, RoutedEventArgs e) 
{ 
    FileOpenPicker openPicker = new FileOpenPicker(); 
    openPicker.ViewMode = Picker.ViewMode.List; 
    openPicker.SuggestedStartLocation = PickerLocationId.PicutresLiibrary; 
    openPicker.FileTypeFilter.Add(".png"); 
    StorageFile.file = await openPicker.PickSingleFileAsync(); 
    OutputTB.text = file.Name; 


    BitmapImage image = new BitmapImage(new Uri(file.path)); 
    OutputImg.Source = image; 
} 

問題是,即使我沒有得到任何錯誤,我的圖片將不會顯示。它將圖片的名稱寫出到OutputTB.text,但圖像只保留爲空。如何使我的選定圖像顯示在OutputImg圖像框中。

據我瞭解,有可能是我在這裏失蹤一個很基本的事情,但它只是意味着是一個學習項目

回答

3

不能使用file.path創建位圖的Uri對象,因爲file.path給人的老式路徑(例如c:\users\...\foo.png)。位圖需要新樣式的uri路徑(例如ms-appdata:///local/path..to..file.../foo.png)。

但是,據我所知沒有任何方法可以爲圖片庫指定新樣式的uri路徑。因此,你必須使用一個簡單的解決方法:既然你已經在文件的引用

,可以改爲可以訪問文件的流,然後將流作爲位圖的源:

StorageFile file = await openPicker.PickSingleFileAsync(); 
OutputTB.text = file.Name; 

// Open a stream for the selected file. 
var fileStream = 
    await file.OpenAsync(Windows.Storage.FileAccessMode.Read); 

// Set the image source to the selected bitmap. 
BitmapImage image = new BitmapImage(); 
image.SetSource(fileStream); 

OutputImg.Source = image; 
相關問題