Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

resources

wpf

I have a DataTemplate 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 ResourceDictionary file and its name is Dictionary1.xaml. I have a data template such as:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">     <DataTemplate x:Key="mytemplate">         <TextBlock Text="Name:" Background="Blue"/>     </DataTemplate> </ResourceDictionary> 

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

like image 819
Embedd_0913 Avatar asked Mar 06 '09 12:03

Embedd_0913


People also ask

What is ResourceDictionary WPF?

In Extensible Application Markup Language (XAML), the ResourceDictionary class is typically an implicit collection element that is the object element value of several Resources properties, when given in property element syntax. For details on implicit collections in XAML, see XAML Syntax Terminology.

How do you add a ResourceDictionary?

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.

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 is a resource dictionary?

A resource dictionary is a repository for XAML resources, such as styles, that your app uses. You define the resources in XAML and can then retrieve them in XAML using the {StaticResource} markup extension and {ThemeResource} markup extension s. You can also access resources with code, but that is less common.


1 Answers

Since Application.Current was null in my case, I've ended up using this:

    var myResourceDictionary = new ResourceDictionary();     myResourceDictionary.Source =         new Uri("/DllName;component/Resources/MyResourceDictionary.xaml",                 UriKind.RelativeOrAbsolute);   

and then getting the specified key I needed by using myResourceDictionary["KeyName"] as TypeOfItem

(source)

like image 158
itsho Avatar answered Oct 12 '22 03:10

itsho