2012-09-07 28 views
0

我每次設置圖像的網格,圖像不會出現,黑色的背景出現網格打開黑色

private void Clk_Enter(object sender, Windows.UI.Xaml.RoutedEventArgs e) 
    { 
     ImageBrush myBrush = new ImageBrush(); 
     BitmapImage bi = new BitmapImage(); 
     bi.UriSource = new Uri(@"C:\Users\Administrator\documents\visual studio 2012\Projects\HelloWorld\HelloWorld\Images\Backgrounds\wallpaper-2022265.jpg",UriKind.Absolute); 
     myBrush.ImageSource = bi; 

     mygrid.Background = myBrush; 


    } 

回答

0

你需要調用BitmapImage.BeginInit()設置了UriSource前,然後調用的BitmapImage .EndInit()之後。

ImageBrush myBrush = new ImageBrush(); 
BitmapImage bi = new BitmapImage(); 
bi.BeginInit(); 
bi.UriSource = new Uri(@"C:\Users\Administrator\documents\visual studio 2012\Projects\HelloWorld\HelloWorld\Images\Backgrounds\wallpaper-2022265.jpg", UriKind.Absolute); 
bi.EndInit(); 
myBrush.ImageSource = bi; 

mygrid.Background = myBrush; 
+0

不能找到這樣的方法「windows.UI.xaml.media.imaging。 bitmapimage'不包含'BeginInit'的定義 –

+1

我假設你在Windows 8上這樣做?你應該更新標籤,因爲它有點不同。 –

+0

是的,它在Windows 8上,如何更新標籤? –

0

我找到了答案只需添加:「MS-APPX」的URI

ImageBrush myBrush = new ImageBrush(); 
BitmapImage bi = new BitmapImage(); 

bi.UriSource = new Uri("ms-appx:/images/wallpaper-2022265.jpg",UriKind.Absolute); 

myBrush.ImageSource = bi; 

    mygrid.Background = myBrush; 
+0

'ms-appx:'很好,但你實際上並不需要在那裏。你可以使用UriKind.Relative,然後使用'/ images/wallpaper-2022265.jpg'。 – mydogisbox

0

之前的問題是,你不使用相對於項目的路徑。在城域應用程序中,您訪問文件系統的方式受到限制。看到我對這個here發表的帖子。

您可以使用項目相對URI在XAML這樣的:

<!--Relative To Project--> 
<Image Margin="5" Source="/Images/favicon.ico" Height="100"/> 

或在這樣的代碼:

bi.UriSource = new Uri("/images/wallpaper-2022265.jpg",UriKind.Relative); 
+0

好的如果我想使用不在解決方案文件夾中的圖像怎麼辦? –

+1

@AR除了在我的答案中鏈接的帖子中列出的那些,請參閱我的回答這裏的另一個問題:http://stackoverflow.com/questions/12020014/uri-schemes-supported-in-windows-8-應用程序/ 12020163#12020163此處的文件訪問限制的更具體信息:http://stackoverflow.com/questions/12220751/open-extern-sqlite-database-in-a-windows-8-metro-app/12220852#12220852 – mydogisbox

+0

爲什麼當我選擇一張照片時背景會顯得黑色,你知道嗎? ..我爲用戶選擇的網格設置了背景..當我選擇一張照片時,背景變黑而不是圖像 –