2017-05-25 61 views
0

我正在使用PRISM6。 在我的模型我有简单:MVVM ObservableCollection项目字符串

public ObservableCollection<Id> Ids { get; } 

在视图模型我想回到这些项目在public ObservableCollection<string> Ids

我怎样才能将其转换为字符串?在这一刻,我有:

private ObservableCollection<string> _ids = new ObservableCollection<string>(); 
public ObservableCollection<string> Ids { 
     get { 
      _ids.Add("Empty"); 
      foreach (var item in _Model.Ids) { 
       _ids.Add(item.ToString()); 
      } 
      return _ids; 
     } 
} 

但是,当我在模型更新我的收藏这是行不通的。

我的旧版本没有转换工作正常。 public ObservableCollection<Id> Ids => _Model.Ids;我需要它在字符串中,因为不知何故我需要将“Empty”添加到组合框。如存在任何更好的解决方案,这请告诉我:)

+0

尝试初始化你的'ObservableCollection'在getter中:'get {_ids = new ObservableCollection (); ...' – Pikoh

+0

@Pikoh它不工作;/ – Zinnerox

+1

当你设置了id时,你很可能忘记了ProperyChange –

回答

0

我敢肯定有出有更好的解决方案,但这里有一个方法,我特别喜欢:

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

这真是太神奇了!非常感谢:) – Zinnerox

+0

@Zinnerox好吧,将它标记为已回答。 –

+0

@FilipCordas哦,对了,对不起,我忘了。 – Zinnerox