Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why setting x:Name on Window.Resources items does not work

Tags:

wpf

i just curious why when i access most controls via x:Name, for resources i do so using x:Key + i cannot access it from code (could using this.Resources["keyName"])

like image 420
Jiew Meng Avatar asked Sep 03 '10 07:09

Jiew Meng


2 Answers

•x:Key: Sets a unique key for each resource in a ResourceDictionary (or similar dictionary concepts in other frameworks). x:Key will probably account for 90% of the x: usages you will see in a typical WPF application's markup.

•x:Name: Specifies a run-time object name for the instance that exists in run-time code after an object element is processed. In general, you will frequently use a WPF-defined equivalent property for x:Name. Such properties map specifically to a CLR backing property and are thus more convenient for application programming, where you frequently use run time code to find the named elements from initialized XAML. The most common such property is FrameworkElement.Name. You might still use x:Name when the equivalent WPF framework-level Name property is not supported in a particular type. This occurs in certain animation scenarios.

for that reason you have to use Key for the Resources

mor on http://msdn.microsoft.com/en-us/library/ms752059.aspx

like image 139
Kishore Kumar Avatar answered Oct 16 '22 13:10

Kishore Kumar


You can access resources on any FrameworkElement as long as the element contains any resources. If defined in your markup, it must have a x:Key and cannot have a x:Name.

If a Button contains the resource for example, you must access it from its Resources collection.

var resource = button.Resources["myKey"];

If you want to find a resource from an object, its parents or the application, use FindResource() instead.

var resource = this.FindResource("myKey");

I don't understand your confusion.

like image 37
Jeff Mercado Avatar answered Oct 16 '22 13:10

Jeff Mercado