2015-02-12 79 views
1

我想在運行時使用C#更改圖像源。我試過這個。在C#中爲windows phone 8.1更改圖像源RT

在MainPage.xaml,

<Image x:Name="myImage" HorizontalAlignment="Left" 
       Height="125" 
       Margin="86,76,0,0" 
       VerticalAlignment="Top" 
       Width="220" /> 
     <Button Content="Button" 
       HorizontalAlignment="Left" 
       Margin="134,230,0,0" 
       VerticalAlignment="Top" 
       Click="Button_Click"/> 

,並在MainPage.xaml.cs

private void Button_Click(object sender, RoutedEventArgs e) 
     { 
      myImage.Source = new BitmapImage(new Uri("/Assets/WorldCupFlags/Sri_Lanka.png", UriKind.Relative)); 
     } 

這表明沒有編譯時錯誤,但是當我運行這個,然後點擊按鈕,它顯示了一個例外。它說「在mscorlib.ni.dll中發生類型'System.ArgumentException'的異常,但未在用戶代碼中處理。」

+0

你有沒有在Windows Phone的應用空白打開? @Peter Torr – Tanvir 2015-02-12 05:48:07

+0

對不起,沒有看到標題中的「RT」(我只是看着標籤)。以下解決方案 – 2015-02-12 05:58:20

回答

4

的提示是例外:

給定的System.Uri不能轉換成Windows.Foundation.Uri

您需要使用絕對URI通用XAML的應用:

myImage.Source = new BitmapImage(new Uri(
    "ms-appx:///Assets/WorldCupFlags/Sri_Lanka.png", UriKind.Absolute)); 
+0

沒有工作或沒有得到任何異常 – Tanvir 2015-02-12 06:19:02

+0

你是什麼意思?上面的黃色文本是您在代碼異常中獲得的文本。灰色文本是你應該替換它的東西。 – 2015-02-12 06:39:09

+0

是的,我用這段代碼替換我的代碼。它不起作用。 – Tanvir 2015-02-12 06:43:21

0

在異步代碼塊,這樣做:

imgMyImageControl.Source = await GetBitmapAsFile("Folder\ImageFileName.png");

的GetBimpageAsFile功能:

/// <summary> 
    /// Gets a bitmap image stored on the local file system 
    /// </summary> 
    /// <param name="strIFile">The input file path name</param> 
    /// <returns>The requested bitmap image, if successful; else, null</returns> 
    public static async Task<BitmapImage> GetBitmapAsFile(string strIFile) 
    { 
     try 
     { 
      StorageFile fOut = null; 
      BitmapImage biOut = null; 
      FileRandomAccessStream fasGet = null; 

      if (!strIFile.Equals("")) 
      { 
       fOut = await Windows.Storage.ApplicationData.Current.LocalFolder.GetFileAsync(strIFile); 
       if (fOut != null) 
       { 
        fasGet = (FileRandomAccessStream)await fOut.OpenAsync(FileAccessMode.Read); 
        if (fasGet != null) 
        { 
         biOut = new BitmapImage(); 

         if (biOut != null) 
         { 
          await biOut.SetSourceAsync(fasGet); 

          return biOut; 
         } 
         else 
          YourApp.App.ShowMessage(true, "Error", "GetBitmapAsFile", "Bitmap [" + strIFile + "] is not set."); 
        } 
        else 
         YourApp.App.ShowMessage(true, "Error", "GetBitmapAsFile", "File stream [" + strIFile + "] is not set."); 
       } 
      } 
      else 
       YourApp.App.ShowMessage(true, "Error", "GetBitmapAsFile", "Input file path name is empty."); 
     } 
     catch (Exception ex) 
     { 
      YourApp.App.ShowMessage(true, "Error", "GetBitmapAsFile", "[" + strIFile + "] " + ex.Message); 
     } 

     return null; 
    } 
相關問題