0

maybe my question is totally stupit but I'm trying to do my best.

All I want to do is to use a function/property of a parent element.

I have prepared a simple example with no sense:

class A
{
    public List<B> myBs = new List<B>();

    public int CountMyBs()
    {
        return myBs.Count;
    }
}

class B
{
    //here i would like to use "CountMyBs()"
}

Thank you!

Edit: I think I have to provide you some more information.

My user is able to drag a value to a canvas. My canvas is in a list of a parent class. Now my canvas wants to know if any other canvas in the list has already the same value.

My idea of realizing:

User does a drag --> Canvas gets an event --> Canvas ask parent class if any other Canvas has already the same value --> decide what to do.

I will post a mor detailed example tomorrow!

MisterPresident
  • 563
  • 7
  • 20
  • I have edited your title. Please have a look at [this Meta SE dicussion](http://meta.stackexchange.com/questions/19190/should-questions-include-tags-in-their-titles). – O. R. Mapper Apr 10 '15 at 19:50

2 Answers2

1

You need something like this:

class A : FrameworkElement
{
    public int CountMyBs() {}
}

class B : FrameworkElement
{
    public void Foo()
    {
        var parent = LogicalTreeHelper.GetParent(this) as A;
        if (parent != null)
        {
            //here i would like to use "CountMyBs()"
            parent.CountMyBs();
        }
    }
}
Dennis
  • 37,026
  • 10
  • 82
  • 150
0

You can pass the instance of A through the constructor of B:

class B
{
    private readonly A a;

    public B(A a)
    {
        this.a = a;
    }

    public int Foo() //Example use
    {
        return 1 + a.CountMyBs();
    }
}

class A
{
    public List<B> myBs = new List<B>();

    public A()
    {
        myBs.Add(new B(this)); //Pass the current A to B
    }

    public int CountMyBs()
    {
        return myBs.Count;
    }
}

But it looks like a bad code smell to me. Unless you have a very specific use case for this, I'd avoid having a child class knowing its parent class only to access a list of itself.

You could simply call your Bs from A, with your method result as a parameter. Feels more natural. It could look like :

class A
{
    public List<B> myBs = new List<B>();

    public A()
    {
        var someB = new B();
        myBs.Add(someB);
        someB.Foo(CountMyBs());
    }

    public int CountMyBs()
    {
        return myBs.Count;
    }
}

class B
{
    public int Foo(int count) //Example use
    {
        return 1 + count;
    }
}
Pierre-Luc Pineault
  • 8,993
  • 6
  • 40
  • 55