標籤:
今天博主在開發一款windows phone應用時,希望實現app背景的更換,思路很簡單。使用ApplicationDataContainer容器儲存我的圖片路徑,每次載入應用時讀取這個路徑以決定我用什麼背景,然後在更換背景時改變這個容器的值就好了。相關代碼如下:
ApplicationDataContainer localsetting = ApplicationData.Current.LocalSettings;
localsetting.Values["Background"] = "ms-appx:///Assets/Images/background2.jpg"; Button btn = sender as Button; if(string.Equals(btn.Tag,"1")) { localsetting.Values["Background"] = "ms-appx:///Assets/Images/background1.jpg"; } else if(string.Equals(btn.Tag,"2")) { localsetting.Values["Background"] = "ms-appx:///Assets/Images/background2.jpg"; } else { localsetting.Values["Background"] = "ms-appx:///Assets/Images/background3.jpg"; }
在載入應用時,把Grid的背景用容器路徑所對應的圖片刷一下,其中的ContentPanel是一個Grid:
if (!localsetting.Values["Background"].Equals(null)) { string strImageUri = localsetting.Values["Background"].ToString(); if (!string.IsNullOrEmpty(strImageUri)) { ImageBrush imageBrush = new ImageBrush(); imageBrush.ImageSource = new BitmapImage(new Uri(strImageUri, UriKind.RelativeOrAbsolute)); ContentPanel.Background = imageBrush; } }
值得注意的是:我的圖片放在工程中下面的Assets檔案夾下面的Image檔案夾中,一開始我容器中存放的值是類似這樣的:
localsetting.Values["Background"] = "Assets/Images/background2.jpg";
然後就會報錯:The given System.Uri cannot be converted into a Windows.Foundation.Uri,現在的Uri定義好像已經修改,具體參考:https://msdn.microsoft.com/zh-cn/library/windows/apps/windows.foundation.uri(v=vs.85).aspx
我的解決方案就是在路徑前面加個ms-appx:///就行了,注意,這是個絕對路徑,UriKind應該設定為UriKind.RelativeOrAbsolute或者UriKind.Absolute
UAP開發錯誤之The given System.Uri cannot be converted into a Windows.Foundation.Uri(windows phone背景更換)