2016-07-06 32 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