Wednesday, December 15, 2010

WPF VisualStateManager GotoState Bug

So, I just wasted a couple of hours trying to figure this one out so I thought I’d post about it so you guys don’t have to waste as much time as I did on it.

The WPF VisualStateManager implementation is still not as rock solid as Silverlight’s implementation (ok, let’s face it, Silverlight’s implementation is far from rock solid too, but it is much better of at this point). If you are trying to call the VisualStateManager.GotoState Method on a Window, you are going to be very very frustrated. Why? Because it doesn’t work. If you are inside a user control, it is fine, but inside of a Window… nope!

Instead of calling this

VisualStateManager.GoToState(this, "stateName", true);

You are going to need to call this

VisualStateManager.GoToElementState(this.RootElement as FrameworkElement, "stateName", true);

That should do it for you. Microsoft is aware of the issue and has promised to fix this, but who knows when that’s going to happen.

Happy state-changing!


WPF - Accessing Resource Dictionaries in Separate Assemblies

There are certain situations where you will need to access resource dictionaries outside of your application. For example, you may want to share one resource dictionary among several applications that share the same styles.

What you want to do is use WPF’s pack URI Scheme.

Remember to include a reference of the assembly containing the resource dictionary (YourAssembly) in the application project. Then, all you have to do is use this rather strange looking syntax to access that resource dictionary within your xaml.

<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceDictionary.xaml"/> 

There are many variations of this syntax that you can use. Which one is right for you depends on exactly what you are trying to do. The above syntax should work for a majority of the situations. Accessing these resources can be done in both xaml and the code behind.

For more information on the pack URI Scheme syntax, follow this link:

Note - this syntax is not only for resource dictionaries. This is useful for accessing several types of data files like images for example. This is commonly used for accessing resource dictionaries, but it is not limited to that.