Reputation: 77
Can I apply "StaticResource" to element in run-time?
I know I can use "StaticResource" to element in xaml files. But, I want to know how to use it from C# (code-behind).
Upvotes: 1
Views: 2890
Reputation: 189457
Not really with the same meaning. StaticResources
are "static" in the sense that their value is resolved during Xaml parsing. The XamlParser will resolve the resource by examining the resource dictionary the ancestor FrameworkElement
Resource
properties that are also in the same xaml and then the Application.Resources if necessary.
If you happen to know where to find the resource you want to assign using C# code then it is as simple as in Claus' answer. However if you only know the name of the resource but not which dictionary its found in then its much tricker.
It is possible to write a routine (you can probably find one in SO or elsewhere on the web) that you can use to hunt up the Visual tree using the VisualTreeHelper
looking at all the Resource
properties along way. You could probably get away with this but be aware that this may search more dictionaries than the original Xaml version would and its possible for you to get some unexpected value.
Upvotes: 2
Reputation: 26344
A StaticResource
is a static defined resource, usually defined in the <X.Resources>
element, for any element or page.
In C# you simply access it with X.Resources["MyResource"]
like you should do {StaticResource MyResource}
.
Upvotes: 3