So the short backstory is that I was messing around with the Media3D library, and had a bunch of .xaml files containing Model3DGroup's as top level elements. So I decided to merge them all into a resource dictionary.
I originally had some code to pull the models out, that looked something like this:
var p = TryFindResource("Sword") as Model3DGroup
if (p!=null) icon.Model=p;
Now, the xaml was littered with x:Name="" attributes, which are not allowed in a ResourceDictionary (but are allowed in a local Resources group). So the behavior I expected from a Try.... method would be to return null, rather than to get an exception.
However, it did throw an exception because of the x:Name="" attributes in the code. I stepped past the code in the debugger, and let it continue running because I wanted to see something else, and lo and behold - my model was there on the screen. The one that threw the exception.
So, creation of the Model from the resource throws an exception, but doesn't fail. TryFindResource therefore does not return null.
In the end, this crazy code works, and the type string will pop out the console, instead of the null you'd expect if the resource sort-of fails, even though the dictionary entries are malformed:
Model3D p = null;
try
{
p = TryFindResource("Sword") as Model3DGroup;
} finally {
}
Console.WriteLine(p);
This is not recommended, of course, and for the record I cleaned up the xaml in my dictionary.
This isn' t specific to the Media3D elements, it works the same for any old UIElement. I'm not sure what other sort of exceptions get thrown but don't cause the resolution to fail, I'm not sure if this behavior is by design or a bug - but I wouldn't rely on it. If the resource was referenced in xaml somewhere, the exception would cause the app to fail - even though the object that threw it is doing just fine.
One thing I do know, is that having to wrap a try around a Try___ is something that really grinds my gears.
Tuesday, October 20, 2009
Subscribe to:
Post Comments (Atom)
1 comment:
Are your sure it wasn't a first chance exception caught by the TryFindResource function internally? Go to "Debug"/"Exceptions" and uncheck "Thrown" for CLR exceptions. As far as I understand the code should work the same without your try {}.
Post a Comment