MVVM ObservableCollection项目字符串
问题描述:
我正在使用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”添加到组合框。如存在任何更好的解决方案,这请告诉我:)
答
我敢肯定有出有更好的解决方案,但这里有一个方法,我特别喜欢:
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();
}
}
尝试初始化你的'ObservableCollection'在getter中:'get {_ids = new ObservableCollection(); ...' –
Pikoh
@Pikoh它不工作;/ – Zinnerox
当你设置了id时,你很可能忘记了ProperyChange –