Question

I want to create several properties on the fly inside the class' constructor and add them to the current class. The property's template is the following

public [PropertyType] [PropertyName]
{
get {return Container.Resolve();}
}

I've read a little about CodeDom and Reflection.Emit but haven't been able to figure out how to use them in this particular use case.

Any clue would be greatly appreciated. Thanks in advance

EDIT: I'm elaborating on the purpose due to the number of questions... I'm trying to implement the base class for a view model locator. The binding in xaml is achieved through referring to a property by its path, therefore it MUST be a property. The types and names of the properties to be added are known only at runtime, therefore I'm using reflection to get them. In short, I need an example of taking a piece of code and compiling it dynamically into the given class.

Was it helpful?

Solution

If you're under C# 4, you can use the new dynamic features for that. Use ExpandoObject or DynamicObject to add properties to your object dynamically. If you then refer to them in XAML, they will get resolved correctly.

In any case, it's not possible to modify existing class. What you can is to create a new class, which can inherit from existing class, and add the properties to that. You should be able to bind to them from XAML.

OTHER TIPS

alternative approach:

you could implement ICustomTypeDescriptor and provide the additional properties

link: Issue with Grid data binding

Bind your xaml stuff to somthing like xml and change xml in the runtime

You can create new calss and inherit it from the current class ,the new class can have the on the fly properties and base class functionality

yes its possible take look at this Help required in adding new methods, properties into existing classes dynamically

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top