Use function of logical parent

237 Views Asked by At

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!

2

There are 2 best solutions below

3
On

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();
        }
    }
}
0
On

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;
    }
}