Application.Properties and custom types

I have a custom type that's basically just a bunch of string properties. If I try to persist the object using Application.Properties (which is a Dictionary<string, object>) in Xamarin Forms, it doesn't work. I would try marking it as Serializable, but that isn't available in a PCL.

What are the requirements for these objects? Or am I limited to simple strings?

Best Answer

Answers

  • MitchMilamMitchMilam USMember ✭✭✭

    @JeremyHerbison can you show us your code?

  • JeremyHerbisonJeremyHerbison CAMember ✭✭

    Just something like this:

    public class UserDetails
    {
            public string Name { get; set; }
            public string Id { get; set; }
    }
    
    ...
    
    // Save
    Application.Current.Properties.Add("UserDetails", new UserDetails{ Name = "Test", Id = "123" });
    await Application.Current.Properties.SavePropertiesAsync();
    
    // Try to Restore
    object restoredUserDetails;
    Application.Current.Properties.TryGetValue("UserDetails", out restoredUserDetails) // Returns false
    
  • adamkempadamkemp USInsider, Developer Group Leader mod

    It looks like it uses DataContractSerializer. You can read about how which types are supported here. Personally I would stick to simple types that are already supported.

  • JeremyHerbisonJeremyHerbison CAMember ✭✭
    edited April 2015

    I tried decorating my class thusly:

    [DataContract]
    public class UserDetails
    {
        [DataMember]
        public string Name { get; set; }
    
        [DataMember]
        public string Id { get; set; }
    }
    

    but it still doesn't work :neutral:

    I'm using a custom type because its constantly changing, and i'm also going to store it in Azure. I certainly could override ToString or something, but i'm still curious about how this feature exactly works.

  • JeremyHerbisonJeremyHerbison CAMember ✭✭
    edited April 2015

    I added 2 helper methods to my UserDetails class to convert to and from the primitive types in a properties dictionary. Seems like the best choice anyway since I might want to do data migrations down the road. Thanks, all. It would be nice to know which primitive types are supported, though.

  • IanGeogheganIanGeoghegan USUniversity ✭✭

    I have had inconsistent results getting my custom types to work with Properties. One build it works; the next it doesn't.

  • DevaPalanisamyDevaPalanisamy GBUniversity ✭✭

    Thanks @Johan_Schoeman . Simple and Elegant Solution.

  • ZaneCampbellZaneCampbell USMember ✭✭

    Thanks @Johan_Schoeman!! Exactly what i needed.

Sign In or Register to comment.