2017-05-25 1 views
0

Ich verwende PRISM6. In meinem Modell Ich habe einfach:MVVM ObservableCollection Elemente zu Zeichenfolge

public ObservableCollection<Id> Ids { get; } 

In Ansichtsmodell würde Ich mag diese Elemente in public ObservableCollection<string> Ids

zurückzukehren Wie kann ich es in einem String konvertieren? In diesem Moment habe ich:

Aber es funktioniert nicht, wenn ich meine Sammlung in Model aktualisieren.

Meine alte Version ohne Konvertierung funktioniert gut. public ObservableCollection<Id> Ids => _Model.Ids; Ich brauche es in String, weil ich irgendwie "leer" Combobox hinzufügen muss. Wenn es irgendeine bessere Lösung für sie mir bitte sagen :)

+0

Versuchen Initialisierung Ihre 'ObservableCollection' im Getter:' get {_ids = new ObservableCollection (); ... ' – Pikoh

+0

@Pikoh Es funktioniert nicht;/ – Zinnerox

+1

Wahrscheinlich haben Sie den PropertyChange vergessen, als die ID gesetzt wurde –

Antwort

0

Ich bin sicher, es gibt viel bessere Lösungen gibt, aber hier ist eine Methode, die ich besonders gerne:

public class MainViewModel 
{ 
    // Source Id collection 
    public ObservableCollection<Id> Ids { get; } 

    // Empty Id collection 
    public ObservableCollection<Id> Empty { get; } = new ObservableCollection<Id>(); 

    // Composite (combination of Source + Empty collection) 
    // View should bind to this instead of Ids 
    public CompositeCollection ViewIds { get; } 

    // Constructor 
    public MainViewModel(ObservableCollection<Id> ids) 
    { 
     ViewIds = new CompositeCollection(); 
     ViewIds.Add(new CollectionContainer {Collection = Empty }); 
     ViewIds.Add(new CollectionContainer {Collection = Ids = ids }); 

     // Whenever something changes in Ids, Update the collections 
     CollectionChangedEventManager.AddHandler(Ids, delegate { UpdateEmptyCollection(); }); 

     UpdateEmptyCollection(); // First time 
    } 

    private void UpdateEmptyCollection() 
    { 
     // If the source collection is empty, push an "Empty" id into the Empty colleciton 
     if (Ids.Count == 0) 
      Empty.Add(new Id("Empty")); 

     // Otherwise (has Ids), clear the Empty collection 
     else 
      Empty.Clear(); 
    } 
} 

enter image description here

+0

Das ist erstaunlich! Vielen Dank :) – Zinnerox

+0

@Zinnerox Nun markieren Sie es als beantwortet dann. –

+0

@FilipCordas Oh, richtig, sorry, ich habe es vergessen. – Zinnerox

Verwandte Themen