Question

Is it possbible to get the Instance of an item, within the CollectionChanged event?

For Example:

public class Foo
{
    public string Name { get; set; }
    public ObservableCollection<Bar> Bars { get; set; }

    public Foo()
    {
        Bars += HelperFoo.Bars_CollectionChanged;
    }
}

public class Bar
{
    public string Name { get; set; }
}

public static class HelperFoo
{
    public static voic Bars_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        //sender is the collection Foo.Bars
        //can I get the Instance of Foo?
    }
}

(I wouldnt mind using reflection)

If this isnt possible is there a way to get the Instance of object that intializes an other object?

For Example:

public class Foo
{
    public string Name { get; set; }

    public Foo()
    {
        var bar = new Bar(); //yes I know, I could write new Bar(this) and provide an overload for this
    }
}

public class Bar
{
    public string Name { get; set; }

    public Bar()
    {
        //Get the Foo, since the constructor is called within Foo, is this possible?
        //without providing an overload that takes an object, and just change it to `(new Bar(this))`
    }
}
Was it helpful?

Solution

I agree with @Gaz but if you are really wanting to do what you describe then add a Dictionary to your HelperFoo class. Then in your Foo class add this as the creator as follows.

public static class HelperFoo
{
    private static Dictionary<ObservableCollection<Bar>, object> lookupCreators = new Dictionary<ObservableCollection<Bar>, object>();

    public static void AddBarsCreator(ObservableCollection<Bar> bars, object creator)
    {
        lookupCreators.Add(bars, creator);
    }

    public static void Bars_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        ObservableCollection<Bar> bars = (ObservableCollection<Bar>)sender;
        if (lookupCreators.ContainsKey(bars))
        {

        }
    }
}

public class Foo
{
    public ObservableCollection<Bar> Bars { get; set; }

    public Foo()
    {
        Bars = new ObservableCollection<Bar>();
        HelperFoo.AddBarsCreator(Bars, this);
        Bars.CollectionChanged += HelperFoo.Bars_CollectionChanged;
    }
}

OTHER TIPS

Your code seems rather oddly structured.

If your HelperFoo class needs to do something with Foo, then pass it Foo, and let it subscribe to Bar events itself.

If HelperFoo shouldn't know anything about Bars, then expose an event on Foo instead and subscribe to that. You can raise then event inside Foo when Bars changes.

Have a read up on the Law Of Demeter.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top