how to get data from ObservableCollection C#

951 views Asked by At

I use function ObservableCollection in one class.

It is defined public to be reachable in another class also.

public ObservableCollection<Node> _nodes;
public ObservableCollection<Node> Nodes
{
     get { return _nodes ?? (_nodes = new ObservableCollection<Node>()); }
}

I want to call this ObservableCollection in another class, how to do it correctly?

I try already with this topic on stackoverflow, but shows me that Node is empty.

1

There are 1 answers

3
Chris Schubert On BEST ANSWER

So you have your Class A, which contains your "nodes".

To access the nodes from Class B a few things need to happen:

  • Class A needs to be a public class that can be instantiated as a member of another class.
  • In Class B, you must instantiate a Class A:

    ClassB {
    
        _private ClassA instanceOfA;
    
        public ClassB() {
            istanceOfA = new ClassA();
        }
    
        private void DoWork()
        {
            foreach(var node in instanceOfA.Nodes)
            {
                // Do Something
            }
        }
    }
    

That will give you access to ClassA's public Nodes property.

Another note - it seems like you are using a getter/setter, but in that case your first

    public ObservableCollection<Node> _nodes;

could be changed to

    private ObservableCollection<Node> _nodes;

to properly encapsulate it. Then you could add a setter to your public property (unless it is readonly):

    public ObservableCollection<Node> Nodes
    {
        get { return _nodes ?? (_nodes = new ObservableCollection<Node>()); }
        set {_nodes = value; }
    }