开发者

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

开发者 https://www.devze.com 2023-01-14 02:10 出处:网络
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\"])•x:Key: Sets a uniq

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"])


•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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消