Comment lier un CollectionContainer à une collection dans un modèle de vue?

J’ai un modèle de vue avec une propriété qui expose une collection de choses. J’ai un ComboBox dont la propriété ItemsSource est liée à cette collection. Maintenant, l’utilisateur peut sélectionner dans la liste.

Je veux autoriser l’utilisateur à effacer la sélection, donc je veux append un élément (c’est-à-dire Null) à ComboBox. C’est assez simple.

J’ai décidé d’essayer d’utiliser CompositeCollection pour le ItemsSource afin que je puisse append les éléments de la liste existante au ComboBox ainsi que l’élément Null supplémentaire.

Après avoir combattu pendant un moment, j’ai décidé de revenir à la documentation sur la classe CompositeCollection . J’ai copié leur exemple et le modifié pour utiliser un modèle de vue plutôt que des ressources statiques.

J’ai découvert qu’aucun élément n’apparaît dans la liste lorsque je lie le CollectionContainer à la liste exposée par ViewModel.

Je ne sais pas comment contourner ce problème et je recherche des conseils sur ce sujet.

Voici mon code XAML:

                       Trying Composite Collections       Other Listbox Item 1 Other Listbox Item 2         

(Comme vous pouvez le voir lorsque je lie le ItemsSource du deuxième ListBox à la propriété list … les éléments apparaissent)

Et voici mon code VB.NET qui fait fonctionner le code XAML:

 Public Class CompositeCollections End Class Public Class GreekGod Public Property GreekName Public Property Name Public Property Description Public Sub New(ByVal greekName As Ssortingng, ByVal englishName As Ssortingng, ByVal description As Ssortingng) Me.GreekName = greekName Me.Name = englishName Me.Description = description End Sub End Class Public Class CompositeCollectionVM Public Property GreekGods As System.Collections.ObjectModel.ObservableCollection(Of GreekGod) Public Sub New() GreekGods = New System.Collections.ObjectModel.ObservableCollection(Of GreekGod) GreekGods.Add(New GreekGod("Ἀφροδίτη (Venus)", "Aphrodite", "Goddess of love and beauty. Although married to Hephaestus she had many lovers, most notably Ares. She was depicted as a beautiful woman usually accompanied by her son Eros. Her symbols include the rose, scallop shell, and myrtle wreath. Her sacred animal is the dove.")) GreekGods.Add(New GreekGod("Ἀπόλλων (Apóllō)", "Apollo", "God of music, healing, plague, prophecies, poetry, and archery; associated with light, truth and the sun. He is Artemis's twin brother and Hermes elder brother, and son of Zeus and Leto. He was depicted as a handsome, beardless youth with long hair and various atsortingbutes including a laurel wreath, bow and quiver, raven, and lyre. Apollo's sacred animal are red cattle.")) GreekGods.Add(New GreekGod("Ἄρης (Mars)", "Ares", "God of war, bloodlust, violence, manly courage, and civil order. The son of Zeus and Hera, he was depicted as either a mature, bearded warrior dressed in battle arms, or a nude beardless youth with helm and spear. His atsortingbutes are golden armour and a bronze-tipped spear. His sacred animals are the vulture, venomous snakes, alligators, and dogs.")) GreekGods.Add(New GreekGod("Ἄρτεμις (Diana)", "Artemis", "Virgin goddess of the hunt, wilderness, wild animals, childbirth and plague. In later times she became associated with the moon. She is the daughter of Zeus and Leto, and twin sister of Apollo. In art she was usually depicted as a young woman dressed in a short knee-length chiton and equipped with a hunting bow and a quiver of arrows. In addition to the bow, her atsortingbutes include hunting spears, animal pelts, deer and other wild animals. Her sacred animals are deer, bears, and wild boars.")) GreekGods.Add(New GreekGod("Ἀθηνᾶ (Minerva)", "Athena", "Goddess of wisdom, warfare, battle strategy, heroic endeavour, handicrafts and reason. According to most traditions she was born from Zeus's head. She was depicted crowned with a crestd helm, armed with shield (Aegis), which holds medusa's head to paralyze her enemies who looked at it and a spear. Her symbols include the aegis and the olive tree. She is commonly shown accompanied by her sacred animal, the snowy owl.")) GreekGods.Add(New GreekGod("Δημήτηρ (Ceres)", "Demeter", "Goddess of agriculture, horticulture, grain and harvest. Demeter is a daughter of Cronus and Rhea and sister of Zeus, by whom she bore Persephone. She was depicted as a mature woman, often crowned and holding sheafs of wheat and a torch. Her symbols are the Cornucopia (horn of plenty), wheat-ears, the winged serpent and the lotus staff. Her sacred animals are pigs and snakes.")) GreekGods.Add(New GreekGod("Διόνυσος (Bacchus)", "Dionysos", "God of wine, parties and festivals, madness, civilization, drunkenness and pleasure at forever young. He was depicted in art as either an older bearded god or a pretty effeminate, long-haired youth. His atsortingbutes include the thyrsus (a pinecone-tipped staff), drinking cup, grape vine, and a crown of ivy. Animals sacred to him include dolphins, serpents, tigers, panthers, and donkeys. A later addition to the Olympians, in some accounts he replaced Hestia.")) GreekGods.Add(New GreekGod("ᾍδης (Hádēs) or Πλούτων (Ploútón)", "Hades or Pluto", "King of the Underworld and god of the dead and the hidden wealth of the Earth. His consort is Persephone and his atsortingbutes are the key of Hades, the Helm of Darkness, and the three-headed dog, Cerberus. The screech owl was sacred to him. Despite being the son of Cronus and Rhea and the elder brother of Zeus, as a chthonic god he is only rarely listed among the Olympians. The name Pluto became more common in the Classical period with the mystery religions and Athenian literature.")) GreekGods.Add(New GreekGod("Ἥφαιστος (Hḗphaistos)", "Hephaestus or Vulcan", "Crippled god of fire, metalworking, stonemasonry, sculpture and volcanism. The son of Hera alone, he is the smith of the gods and the husband of the adulterous Aphrodite. He was usually depicted as a bearded man holding hammer and tongs—the tools of a smith—and riding a donkey. His symbols are the hammer, tongs, and anvil. His sacred animals are the donkey, the guard dog and the crane. When he was born, he was thrown off of Mount Olympus by Hera as he was considered ugly.")) GreekGods.Add(New GreekGod("Ἥρα (Juno)", "Hera", "Queen of marriage, women, childbirth, heirs, kings and empires. She is daughter of Cronus and Rhea. She was usually depicted as a beautiful woman wearing a crown and veil and holding a royal, lotus-tipped staff. Her sacred animals are the cow, the peacock. She is the eternal wife of Zeus.")) GreekGods.Add(New GreekGod("Ἡρμῆς (Mercury)", "Hermes", "God of travel, messengers, trade, thievery, cunning wiles, language, writing, diplomacy, athletics, and animal husbandry. He is the messenger of the gods, a psychopomp who leads the souls of the dead into Hades' realm, and the son of Zeus and Maia. He was depicted either as a handsome and athletic beardless youth, or as an older bearded man. His atsortingbutes include the herald's wand or caduceus, winged sandals, and a traveler's cap. His sacred animals are the tortoise, the ram, and the hawk.")) GreekGods.Add(New GreekGod("Ἑστία (Vesta)", "Hestia", "Virgin goddess of the hearth, home and cooking. She is a daughter of Rhea and Cronus and sister of Zeus. She was depicted as a modestly veiled woman, whose symbols are the hearth and kettle. In some accounts, she gave up her seat as one of the Twelve Olympians to tend to the sacred flame on Mount Olympus for Dionysus.")) GreekGods.Add(New GreekGod("Ποσειδῶν (Neptune)", "Poseidon", "God of the sea, rivers, floods, droughts, storms, earthquakes, and the creator of horses; known as the 'Earth Shaker' or 'Storm Bringer'. He is a son of Cronus and Rhea and brother to Zeus and Hades. In classical artwork, he was depicted as a mature man of sturdy build with a dark beard, and holding a sortingdent. The horse and the dolphin are sacred to him.")) GreekGods.Add(New GreekGod("Ζεύς (Jupiter)", "Zeus", "The king of the gods, the ruler of Mount Olympus and the god of the sky, weather, thunder, law, order, and fate. He is the youngest son of Cronus and Rhea, whom he overthrew after Cronus swallowed his brothers and sisters and he is brother-husband to Hera. In artwork, he was depicted as a regal, mature man with a sturdy figure and dark beard. His usual atsortingbutes are the royal sceptre and the lightning bolt. His main atsortingbute was his master bolt. His sacred animals are the eagle and the bull.")) End Sub End Class 

Merci de votre aide!


La réponse de HB a parfaitement fonctionné. Voici le XAML de travail mis à jour:

                            Other Listbox Item 1 Other Listbox Item 2   Trying Composite Collections         

    CompositeCollection n’a pas de DataContext , les liaisons dans CollectionContainers ne fonctionneront pas si elles sont liées directement à une propriété (qui utilise implicitement DataContext comme source).

    Vous devez spécifier explicitement une source, je vous suggère de nommer le contrôle avec votre DataContext et d’utiliser x:Reference pour l’obtenir ( ElementName ne fonctionnera pas ) ou vous utilisez un StaticResource , par exemple


    Notez que lorsque vous utilisez x:Reference le compilateur vous interrompt facilement avec des erreurs de dépendance cycliques, pour éviter que celles-ci placent votre CompositeCollection dans les ressources du contrôle référencé, puis insérez-le partout où il appartient en utilisant l’extension de balisage StaticResource .

    Un IMultiValueConverter est un bon ajustement pour CompositeCollection mais pas pour votre cas spécifique où vous ajoutez des éléments dans xaml.


     using System; using System.Collections; using System.Globalization; using System.Windows.Data; public class CompositeCollectionConverter : IMultiValueConverter { public static readonly CompositeCollectionConverter Default = new CompositeCollectionConverter(); public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var compositeCollection = new CompositeCollection(); foreach (var value in values) { var enumerable = value as IEnumerable; if (enumerable != null) { compositeCollection.Add(new CollectionContainer { Collection = enumerable }); } else { compositeCollection.Add(value); } } return compositeCollection; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture) { throw new NotSupportedException("CompositeCollectionConverter ony supports oneway bindings"); } } 


          ...   ...