Bovi_Khurja Bovi_Khurja - 1 year ago 196
C# Question

How can I access ResourceDictionary in wpf from C# code?

I have a

defined in a xaml file that I want to access via C# code.
Can anyone please tell me how can I access it?
I added a new
file and its name is Dictionary1.xaml.
I have a data template such as:

<ResourceDictionary xmlns=""
<DataTemplate x:Key="mytemplate">
<TextBlock Text="Name:" Background="Blue"/>

not I have a
called listBox1 and I want to assign it to it's
but I'm not getting how can i do it?

Answer Source

Where exactly are you defining it?

If you define it in the ResourceDictionary of your object, then


should work. If you are defining it as a member of something else, like say, an ItemsControl, you need to get a handle to the ItemsControl instance and call the ItemTemplate property.

Edit: Ok, I think we're getting somewhere. So you are defining a ResourceDictionary in its own file. Before you can use it in your UI and access it from your code behind, you need to merge that ResourceDictionary into your application. Are you doing this?

If you are, then the next step is to get this resource. Each FrameworkElement has a method called FindResource. This method is great because it walks up the ResourceDictionary tree and attempts to locate the resource with the key. So, if you want to access this resource from a UserControl, you can do the following in the code behind:


If this doesn't work for you, please show us exactly how you are declaring this resource dictionary and how it is getting merged into your application's resources.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download