Poma
Poma

Reputation: 8484

How to create instance of class in 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.

Upvotes: 7

Views: 14539

Answers (3)

Ben Steele
Ben Steele

Reputation: 11

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()

Upvotes: 1

Poma
Poma

Reputation: 8484

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.

Upvotes: 1

BigL
BigL

Reputation: 1631

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.

Upvotes: 6

Related Questions