2016-07-06 44 views
0

我需要一个字典,该字典的Type为键和Control为值。例如对于字符串类型,控件将是TextBox;对于布尔类型,控件将是单选按钮,依此类推...... 问题是当我声明像Dictionary<Type, Control>这样的字典时,并尝试添加TextBox,例如它说TextBox是一种类型,它在给定的背景。 任何想法?将System.Windows.Controls存储到字典中

回答

0

您必须声明Dictionary<Type, Type>而不是Dictionary<Type, Control>因为TextBoxType

private static Dictionary<Type, Type> s_ControlTypes = new Dictionary<Type, Type>() { 
    {typeof(string), typeof(TextBox)}, 
    {typeof(bool), typeof(RadioButton)}, 
}; 

,然后用它

// Let's create a control for, say, `bool` type: 
Control ctrl = Activator.CreateInstance(s_ControlTypes[typeof(bool)]) as Control; 
0
Dictionary<Type, Control> dictionary = new Dictionary<Type, Control>(); 
    dictionary.Add(typeof(string), textBox); 
    dictionary.Add(typeof(bool), checkBox); 
0

看起来像你想添加Control型(字面)到字典,它应该包含Control实例:

var dictionary = new Dictionary<Type, Control>(); 
dictionary.Add(typeof(string), TextBox); 

你不能这样做。你需要要么把特定实例的Control,或者,如果这仅仅是一个有些地图进一步参考,重新申报词典:

var dictionary = new Dictionary<Type, Type>(); 

类型填充:

dictionary.Add(typeof(string), typeof(TextBox)); 
// and so on