2015-07-13 79 views
3

我有一個文件夾結構中的一些圖像,我試圖加載和更改我的代碼使用c#(而不是xaml)的背景中。從資源加載圖像到圖像控制

我沒有這樣的運氣,要麼收到異常拋出或預加載的圖像應該改變時不可見。我在這裏嘗試了各種問題的代碼示例,但我仍然沒有運氣。

文件夾結構 - >Resources/Images/Themes/{mytheme}.png 生成操作 - >資源 (所有已被添加作爲一種資源來resources.resx太)

我現在已經是代碼..

var themeImage = new BitmapImage(); 
var filename = string.Format("{0}{1}.png", cmbBaseThemes.SelectedValue.ToString(), cmbAccentColors.SelectedValue.ToString()); 
themeImage.BeginInit(); 
themeImage.UriSource = new Uri(@"/ZApp;component/Resources/Images/Themes/" + filename, UriKind.RelativeOrAbsolute); 
themeImage.EndInit(); 
imgThemeStyle.Source = themeImage; 

但這段代碼總是給我例外:「無法找到資源'resources/images/themes/lightindigo.png'」。

+0

什麼*所有已被添加爲資源resources.resx too *意味着什麼? – Sinatr

回答

0

在後面的代碼,你將不得不使用一個完全合格的Resource File Pack Uri

themeImage.UriSource = new Uri(
    "pack://application:,,,/ZApp;component/Resources/Images/Themes/" + filename); 

您也可以通過避免BeginInit/EndInit電話BitmapImage構造函數,需要一個Uri參數:

imgThemeStyle.Source = new BitmapImage(new Uri(
    "pack://application:,,,/ZApp;component/Resources/Images/Themes/" + filename)); 
+0

沒有喜悅 - 「URI無效:無法分析權限/主機。」 – Andy

+0

編輯答案。它錯過了雙斜線。 – Clemens

+0

是的!這看起來正在工作! :) – Andy

0

您可能會在創建時缺少一些參數。

試試這個方法:

img = new BitmapImage(); 
img.BeginInit(); 
img.CacheOption = BitmapCacheOption.OnLoad; 
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache; 
img.UriSource = new Uri(@"/ZApp;component/Resources/Images/Themes/" + filename, UriKind.RelativeOrAbsolute); 
img.EndInit();