C #: associa l'hashtable alla domanda della casella combinata
-
05-07-2019 - |
Domanda
public class FontType
{
...
public String Name { get { return _name; } }
public String DisplayName { get { return _displayName; } }
public Font UseFont { get { return _font; } }
}
bindFontTypes.DataSource = availableFonts;
comboFontType.DataSource = bindFontTypes;
comboFontType.ValueMember = "Key";
comboFontType.DisplayMember = ...???;
Qui bindFontTypes
è BindingSource. availableFonts
è un Hashtable in cui le chiavi sono stringhe e i valori sono oggetti di FontType. Per comboFontType.DisplayMember
voglio usare la proprietà .DisplayName degli oggetti. Come posso specificarlo? È possibile?
Soluzione
Potrebbe funzionare se imposti
comboFontType.DisplayMember = "Value"; // FontType
e sovraccarico ToString ()
per FontType
.
In alternativa a ToString () è possibile gestire l'evento Format della casella combinata.
Ma non sono nemmeno sicuro che il databinding funzioni in questo modo.
Altri suggerimenti
Usando DisplayMember = " Value.DisplayName "
sto ottenendo l'ultimo aggiunto a Hashtable ... sto lavorando per ottenerli tutti ....
Questo è quello che ho fatto ... ma riesco a legare solo l'ultimo elemento nella Hashtable ....
BindingSource src = new BindingSource();
src.DataSource = new Hashtable
{
{
"blah",
new FontType
{
Name = "newFont",
DisplayName = "new Font"
}
},
{
"another",
new FontType
{
Name = "anotherFont",
DisplayName = "another Font"
}
}
};
comboBox1.DataSource = src;
comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value.DisplayName";