Windows Phone App数据

时间:2015-06-12 04:18:40

标签: c# windows windows-phone-8

我想要做的是我想在我的应用中为我的用户维护个人资料照片。 用户可以从本地图片库中进行拍照。因此,无论何时加载应用程序,都应检查本地应用程序数据是否存在图片,如果存在,则应将图像设置为该图片。我试过这样做,但它没有用。

// Saving
BitmapImage bitmapImage = image.Source as BitmapImage;
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
string path = bitmapImage.UriSource.ToString();
localSettings.Values["ProfilePic"] = path;

// In constructor retrieving like this.
string sourceVal = localSettings.Values["ProfilePic"] as string;

if (sourceVal != null) {
    Image img = new Image();
    BitmapImage bi = new BitmapImage();
    Uri uri = new Uri(sourceVal);
    bi.UriSource = uri;
    img.Source = bi;
}

它会抛出异常,任何人都可以使用C#给出适当的代码吗?

发生了{p> System.NullReferenceException

1 个答案:

答案 0 :(得分:0)

在这里和那里修改你的代码,它对我来说很好。看看

XAML

    <Image Name="img" Height="100" Width="100"/>

代码背后:

// define on top
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;


//in constructor or in OnNavigatedTo()
 string sourceVal = localSettings.Values["ProfilePic"] as string;
 if (sourceVal != null)
        {
            //  Image img1 = new Image();
            BitmapImage bi = new BitmapImage();
            Uri uri = new Uri(sourceVal, UriKind.Relative);
            bi.UriSource = uri;
            img.Source = bi;
        }
        else
        {
            // hardcoding image source for testing. You can set image here from gallery
            img.Source = new BitmapImage(new Uri("/Assets/AlignmentGrid.png", UriKind.Relative));
        }

// Save image (in OnNavigatedFrom())
BitmapImage bitmapImage = img.Source as BitmapImage;
string path = bitmapImage.UriSource.ToString();
localSettings.Values["ProfilePic"] = path;

试试这个并告诉我是否有任何问题。