Click here to Skip to main content
Click here to Skip to main content

WPF Persistency

By , 3 Jan 2013
 

Introduction

While looking for a way to persist state for a WPF application, I found the article WPF Control State Persistency from Tomer Shamam. Although the article was great and easy to use, I was inspired by a comment from Robert Cannon to try an alternate implementation.

The main differences are:

  • Automatic key generation
  • No need to explicitly load/save persisted data
  • No mode support (Memory/Persist)
  • Only one (static) dictionary for the whole project
  • Direct binding to back storage

Using the code

The following steps have to be done to use the code:

  • Copy attached file UserSettings.cs into your project
  • Add a namespace declaration to the XAML file xmlns:app="clr-namespace:WpfPersist".
  • Use the UserSettings markup extension (and provide default value) where appropriate.

The markup snippet below shows how to use the UserSettings markup extension to store Window Size and Position:

<Window x:Class="WpfPersist.Demo.Window1"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:app="clr-namespace:WpfPersist"
   Title="WpfPersist.Demo"
   Height="{app:UserSettings Default=300}" 
   Width="{app:UserSettings Default=400}"
   Top="{app:UserSettings}" Left="{app:UserSettings}"
   >
   <Grid>
   ...
   </Grid>
</Window>

How it Works?

The main difference between this implementation and the one from Tomer is that I try to automatically derive a key for persistent storage. The snippet below shows how I do that for objects that derive from UIElement:

IUriContext uriContext = (IUriContext)serviceProvider.GetService
                            (typeof(IUriContext));
key = string.Format("{0}.{1}[{2}].{3}",
   uriContext.BaseUri.PathAndQuery,
   targetObject.GetType().Name, ((UIElement)targetObject).PersistId,
   targetProperty.Name);

Objects that have a parent in the logical tree (like ColumnDefinition) also can have the key automatically generated:

IUriContext uriContext = (IUriContext)serviceProvider.GetService
                            (typeof(IUriContext));
UIElement parent = (UIElement)LogicalTreeHelper.GetParent(targetObject);
int i = 0;
foreach (object c in LogicalTreeHelper.GetChildren(parent))
{
   if (c == targetObject)
   {
      key = string.Format("{0}.{1}[{2}].{3}[{4}].{5}",
         uriContext.BaseUri.PathAndQuery,
         parent.GetType().Name, parent.PersistId,
         targetObject.GetType().Name, i,
         targetProperty.Name);
      break;
   }
   i++;
}

Unfortunately I found no way to derive a key for GridViewColumn objects.
For debug builds, the code issues an assert on properties where no key can be generated. In release builds, the code silently ceases functioning.
To work around this, there is a Key property on the markup extension. Note that the key should be unique for the whole project and not only the XAML file. The snippet below shows how to apply the Key property:

<GridViewColumn
   DisplayMemberBinding="{Binding Mode=OneTime,Path=ProcessName}"
   Header="ProcessName"
   Width="{app:UserSettings Default=100, 
                Key=Window1.ListView0.Col0.Width }" />

Another difference between the two implementations is that I use an ApplicationSettingsBase derived internal class for persistent storage. The current implementation saves the data automatically when the main Window is closing. Meaning that there is no need to provide additional code to save/load the data.

Points of Interest

The biggest shortcoming of this implementation is that I found no way to persist ordering for GridViewColumn's.
For Winforms, the designers provided the DisplayIndex property on the DataGridViewColumn object that could be used for that, but in WPF there is no such thing. The WPF-Designers obviously felt that a modified Columns collection should be enough.

Another issue that nearly drove me nuts was the XmlnsDefinitionAttribute that Tomer is using. It took me quite a while to figure out that this attribute works only for code that is implemented in a different assembly.

If anyone finds a good solution to persist column ordering or finds a way to generate a key for the GridViewColumn property, I'm more than happy to hear about it.

Change Log

  • 7 Aug 2007: Initial Version
  • 3 Jan 2013: Update to VS2010 (recommended fix for VS-Designer)

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Reto Ravasio
Switzerland Switzerland
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionErrors and Warningsmemberyolki201219 Nov '12 - 0:52 
Error:
Error 3 Object reference not set to an instance of an object.
 

Warning 2   'System.Windows.UIElement.PersistId' is obsolete: 'PersistId is an obsolete property and may be removed in a future release.  The value of this property is not defined.'   
 

though program runs file
 
what is cause of error and warning and is there any way to get rid of them ?
I am using VS2012 .net4.5
AnswerRe: Errors and WarningsmemberFernando E. Braz22 Mar '13 - 7:02 
works fine. i have vs2010 and i am not having that warning.
BugBug fix : avoid exception in design modememberchprogmer6 Jun '12 - 3:12 
As you can see in the demo app, you cannot edit the XAML file in the VS' designer because it causes exceptions in UserSettings.cs
 
Fortunately this problem is easy to be solved.
Just insert these lines:
 
if (System.Reflection.Assembly.GetEntryAssembly()==null) // Design mode (the XAML designer called it).
  return ConvertFromString(targetObject, targetProperty, defaultValue);
 
just before the first occurrence of this line:
 
if (key == null)
 
Now you can play with the "default" values and watch the result at real time.
 
I hope that helps.
 
Tested with VS 2010, but not in Blend.
GeneralRe: Bug fix : avoid exception in design modememberyolki201219 Nov '12 - 0:49 
why error
Error 3 Object reference not set to an instance of an object.
comes prograM RUNS Fine but this error comes in warning ang errors
 
and warning
 
Warning 2 'System.Windows.UIElement.PersistId' is obsolete: 'PersistId is an obsolete property and may be removed in a future release. The value of this property is not defined.'
 
is ther nay way to get rid of it.
GeneralRe: Bug fix : avoid exception in design modememberchprogmer29 Nov '12 - 13:44 
1. For "PersistId is an obsolete property.." warning, it cannot be avoided since this property is necessary to identify the element but it is officially obsolete (although it still exists in dotnet 4).
2. For your error "Object reference not set", please give more information.
NewsRe: Bug fix : avoid exception in design modememberReto Ravasio3 Jan '13 - 14:07 
Thanks for the input. I finally found the time to update the article.
Instead of your solution which I think fails when hosted by native code, I've put in the following:
if (DesignerProperties.GetIsInDesignMode(targetObject))
   return ConvertFromString(targetObject, targetProperty, Default);
Works perfect!
SuggestionLicensememberchprogmer6 Jun '12 - 0:31 
Hello
 
Thank you for this nice work.
 
Could you consider to add a license to your work ?
I suggest the Ms-PL for its guarantees against patents, or the CPOL.
 
Other suggestion: update the source code using the previous questions/suggestions.
 
Thanks
GeneralBe carful with PersistId property because it is obsoletememberido.ran24 Jun '10 - 6:02 
Thank you very much for the article.
I just want to make sure people using this code pay attention to the user of PersistId property which is marked as Obsolete and will not exist in future releases of WPF.
 
Maybe you can change the impl. to use x:Uid instead.
 
Ido
GeneralRe: Be carful with PersistId property because it is obsoletememberReto Ravasio24 Jun '10 - 11:55 
I'm aware of this. I left the warning in place on purpose so that users compiling the application are notified about this potential pitfall. I didn't use x:Uid originally because they are not set automatically. but today as I now have a number of localizable applications I think your idea of using x:Uid is looking rather promising and I'l definitely have a closer look when MS makes PersistId inoperable.
Thanks a lot for the input.
reto
AnswerRe: Be carful with PersistId property because it is obsoletememberReto Ravasio3 Jan '13 - 5:02 
While updating the article I had a go at using the x:Uid property. It looks like this is leading nowhere Frown | :-(
I've also found your blog post[^] about this issue. I probably would have spent even more time without finding it Smile | :)

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web04 | 2.6.130523.1 | Last Updated 3 Jan 2013
Article Copyright 2007 by Reto Ravasio
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid