Silverlight – Converting text / Type to an object

28 02 2010

Problem:

Let’s say you have a series of ChildWindows that each show some data. e.g Add/Edit Customer, Add/Edit Vendor and etc.

Each ChildWindow has a name e.g. AddCustomer, AddVendor.

And you also have a series of Hyperlinks that are used to show these childwindows. Suppose you want to do is to have “one” method that all these Hyperlinks call to open their related childwindow. Each Hyperlink tag is holding the same name of the ChildWindow, i.e. AddCustomer, AddVendor as above.

Solution:

You can use Activator.CreateInstance which create object from type

    string childWindowTypeName = "ChildWindow1";//hyperlink.Tag.ToString()
    string nameSpace = this.GetType().Namespace;

    Type type = Type.GetType(string.Format("{0}.{1}", nameSpace, childWindowTypeName));

    ChildWindow c = Activator.CreateInstance(type) as ChildWindow;
    c.Show();
Advertisements

Actions

Information

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




%d bloggers like this: