本文介绍了如何在可观察集合中设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在可观察集合中设置值?
我有这段代码:
How set values in observable collection ?
I have this code:
private ObservableCollection<Workspace> _OpenWorkspaces;
public ObservableCollection<Workspace> OpenWorkspaces {
get { return _OpenWorkspaces; }
set { _OpenWorkspaces = value; }
}
How Can I set the values ? (like this doesn't works)
OpenWorkspaces.id =1;
OpenWorkspaces.Name ="Jon";
推荐答案
using System.Collections.ObjectModel;
namespace TestObservableCollection
{
public class WorkSpace
{
public int ID { set; get; }
public string Name { set; get; }
public WorkSpace(int id, string name)
{
ID = id;
Name = name;
}
}
public class WorkSpaces : ObservableCollection<WorkSpace>
{
public new void Add(WorkSpace workspace)
{
base.Add(workspace);
}
public new void Remove(WorkSpace workspace)
{
base.Remove(workspace);
}
}
}
表单中的示例测试:
using TestObservableCollection;
private void TestObsCollection()
{
WorkSpaces ws = new WorkSpaces();
ws.CollectionChanged += ws_CollectionChanged;
WorkSpace wsp = new WorkSpace(id: 100, name: "test");
ws.Add(wsp);
ws.Remove(wsp);
}
// Collection Changed EventHandler
private void ws_CollectionChanged(object sender,
System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
WorkSpace ws;
switch (e.Action.ToString())
{
case "Add":
ws = e.NewItems[0] as WorkSpace;
Console.WriteLine("Action: {0} ID: {1} Name: {2}", e.Action, ws.ID, ws.Name);
break;
case "Remove":
ws = e.OldItems[0] as WorkSpace;
Console.WriteLine("Action: {0} ID: {1} Name: {2}", e.Action, ws.ID, ws.Name);
break;
}
}
测试的控制台输出:
Action: Add ID: 100 Name: test
Action: Remove ID: 100 Name: test
这篇关于如何在可观察集合中设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!