2016-07-06 8 views
0

Ich brauche ein Wörterbuch, das Type als Schlüssel und Control als Wert haben wird. Zum Beispiel für den String-Typ ist das Control TextBox; für Typ von Boolean, das Steuerelement wird Radio-Button, und so weiter ... Das Problem ist, wenn ich Wörterbuch wie Dictionary<Type, Control> deklarieren, und versuchen, TextBox zum Beispiel zu sagen, dass TextBox ein Typ ist, der in einem nicht gültig ist gegebener Kontext. Irgendwelche Ideen?Speichern von System.Windows.Controls in einem Wörterbuch

Antwort

0

Sie haben Dictionary<Type, Type> statt Dictionary<Type, Control> seit TextBox zu erklären ist Type:

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

Und dann verwenden Sie es

// 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

Sieht aus wie Sie versuchen, Control Typ hinzufügen (wörtlich) zum Wörterbuch, das Control Instanzen enthalten sollte:

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

Sie können dies nicht tun. Sie müssen entweder bestimmte Instanz Control zu setzen, oder, wenn dies nur einige der Karte für weitere Referenz, Re-declare Wörterbuch ist:

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

und füllen es mit Typen:

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