今天博主在开发一款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
时间: 2024-10-10 15:17:54