如何在运行时获取类的实例知道它的(字符串)名称?

时间:2011-06-03 15:56:17

标签: c# reflection silverlight-4.0 user-controls

大家。我使用WP7。 我有ListBox

ListBox中的项目必须看起来非常不同。每个元素都是特殊的。

我做了什么。我为ListBoxItem创建了一个简单的 dataTemplate 。只有 ContentPresenter ,仅此而已。

内容属性 ContentPresenter 绑定到 DataContext.Content

此外,我创建了几个userConrols,代表每个元素的特殊内容。

specialObject one = new specialObject();
one.textString = "one"; //data of object
oneButtonPanel b1 = new oneButtonPanel(); //look of object

specialObject two = new specialObject();
two.textString = "two"; //data of object
two_butonsPanel b2 = new two_butonsPanel(); //look of object

one.Content = b1; //set up Content property
b1.DataContext = one;
two.Content = b2;
b2.DataContext = two; //set up Content property        

ObservableCollection<specialObject> colItems = new ObservableCollection<specialObject>() { one, two };
myListBox.ItemsSource = colItems;

一切正常。但我不知道实际上我必须创建哪个UserControl

two_butons b2 = new two_butons(); // Any other class can be here. I know only its string name - "two_butons"

如何获取类实例,只知道它的名称?

或者 - 我可以通过其他方式获取userControl实例吗?

非常感谢。

1 个答案:

答案 0 :(得分:2)

您可以调用assembly.GetType(someString),其中assembly是包含该类型的Assembly实例。 (例如,typeof(YourOtherType).Assembly