Click here to Skip to main content
15,890,123 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How set values in observable collection ?

I have this code:

C#
private ObservableCollection<Workspace> _OpenWorkspaces;
public ObservableCollection<Workspace> OpenWorkspaces {
	get { return _OpenWorkspaces; }
	set { _OpenWorkspaces = value; }
}

SQL
How Can I set the values ? (like this doesn't works)

C#
OpenWorkspaces.id =1;
OpenWorkspaces.Name ="Jon";
Posted

C#
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);
        }
    }
}
Sample test in a Form:
C#
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;
    }    
}
Console output from test:
Action: Add ID: 100 Name: test
Action: Remove ID: 100 Name: test
 
Share this answer
 
v2
You add items in an observable collection, not single values. Have a look at the example in the end of ObservableCollection<t> Class[^] documentation
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900