Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a resource via codebehind in WPF

I have a custom collection defined in my window resources as follows (in a Sketchflow app so the window is actually a UserControl):

<UserControl.Resources>     <ds:MyCollection x:Key="myKey" x:Name="myName" /> </UserControl.Resources> 

I want to be able to refer to this collection in the codebehind, which I expected would be by the x:Name, but I can't seem to access it.

I can get a reference to it using

myRef = (MyCollection) this.FindName("myKey"); 

but this seems hackish. Is this bad practice, and what would be better? Thanks :)

like image 279
randomsequence Avatar asked Jan 22 '10 14:01

randomsequence


People also ask

How do I add a resource to a project in WPF?

To add a Resource Dictionary into your WPF application, right click the WPF project > add a Resource Dictionary. Now apply the resource "myAnotherBackgroundColor" to button background and observe the changes.

What type of Resources are available in WPF?

WPF supports different types of resources. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs.

What is static resource and DynamicResource in WPF?

StaticResource are retrieved only once by the referencing element and used for entire life of the resource. On the other hand, DynamicResource are acquired every time the referenced object is used.

How do I add Resources to XAML dictionary?

Tip You can create a resource dictionary file in Microsoft Visual Studio by using the Add > New Item… > Resource Dictionary option from the Project menu. Here, you define a resource dictionary in a separate XAML file called Dictionary1. xaml.


1 Answers

You should use System.Windows.Controls.UserControl's FindResource() or TryFindResource() methods.

Also, a good practice is to create a string constant which maps the name of your key in the resource dictionary (so that you can change it at only one place).

like image 181
japf Avatar answered Sep 19 '22 18:09

japf