Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create instance of class in XAML?

Tags:

c#

.net

wpf

xaml

I want to create simple utility class that has no visual elements and create it in XAML so I can define databindings. I tried to create class derived from DependencyObject and create it in Window.Resources section but it doesn't call any constructor.

like image 401
Poma Avatar asked Dec 29 '11 13:12

Poma


3 Answers

You can instantiate your class in the app.xaml, just add your namespace to it with

xmlns:yourNamespace="clr-namespace...."

It is easy the intellisense helps.

And then in Application.Resources you create your class

<Application.Resources>
   <yourNamespace:YourClass x:Key="yourClassInstanteName" />      
</Application.Resources>

I hope this helps you.

like image 172
BigL Avatar answered Sep 20 '22 16:09

BigL


Looks like instances are created when you actually use them. I've found dirty workaround for this problem - to place FindResource("myClass"); in main form constructor.

like image 37
Poma Avatar answered Sep 18 '22 16:09

Poma


I know i am posting on an old Question but i came across this while trying to find the answers myself. The code big L posted was indeed correct:

xmlns:yourNamespace="clr-namespace...."

Place a copy in the Application Resources:

<Application.Resources>
   <yourNamespace:YourClass x:Key="yourClassInstanteName" />      
</Application.Resources>

The additional key to this information is that the class needs to have a default constructor. So in the Class source you should have a method like so:

public yourClassName()
like image 23
Ben Steele Avatar answered Sep 21 '22 16:09

Ben Steele