I understand that calling FindResource() on a FrameworkElement (e.g. a Window) can be used to find a resource in the FrameworkElement's ResourceDictionary.
For example, I've used it many times to access a Style through code to add a new Setter to the Style dynamically. I always pass the x:Key value of the Style as a string into the FindResource() method. Like... Style style = w.FindResource("GridDescriptionColumn") as Style;
My question is, I noticed that FindResource() accepts an argument of type object and not an argument of type string. I can't for the life of my think of a reason I would call FindResource() with an argument that is not a string. It makes me think that I may unaware of other ways to use FindResource().
Does anyone know why FindResource() accepts a parameter type of object and not string? If so, what would be an exam开发者_Python百科ple of calling FindResource() with a parameter type other than a string?
Thanks.
A resource can have any object as a key. Adding a resource with an object key in code behind is easy and can be useful. In XAML, most of the time you're using a string as the x:Key
. However there's a common case where the key is not a string and you might even have used without realizing it:
When a Style
has no x:Key
, it's applied to every instance of its TargetType
. But there's an implicit key added by the compiler: the type of the TargetType
itself.
In short, writing <Style TargetType="{x:Type Button}" />
in a resources section is exactly the same as writing <Style TargetType="{x:Type Button}" x:Key="{x:Type Button}" />
. To get this resource back from code, you have to use FindResource(typeof(Button))
, passing a Type
and not a string
.
精彩评论