是否可以在CollectionChanged事件中获取项目的Instance
?
例如:
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?
}
}
(我不介意使用反射)
如果这不可能有办法获得初始化其他对象的对象实例吗?
例如:
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))`
}
}
答案 0 :(得分:1)
你的代码看起来很奇怪。
如果您的HelperFoo
课程需要对Foo
执行某些操作,请将其Foo
传递给它,并让它自己订阅Bar
个事件。
如果HelperFoo
不了解Bars
的任何内容,请在Foo
上公开一个事件并订阅该事件。当Foo
更改时,您可以在Bars
内提出事件。
答案 1 :(得分:1)
我同意@Gaz但是如果你真的想要做你所描述的,那么在你的HelperFoo类中添加一个Dictionary。然后在你的Foo类中添加它作为创建者,如下所示。
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;
}
}