如何在可观察集合中设置值? [英] How set values in observable collection ?

查看:62
本文介绍了如何在可观察集合中设置值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在可观察集合中设置值?



我有这段代码:


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


您可以在可观察集合中添加项目,而不是单个值。看一下 ObservableCollection< t>结尾处的示例。班级 [ ^ ]文档
You add items in an observable collection, not single values. Have a look at the example in the end of ObservableCollection<t> Class[^] documentation


这篇关于如何在可观察集合中设置值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆