C#委托方法丢失类字段/事件丢失类字段
问题描述:
我有几个Action1类的实例。他们每个人都应该在完成动画后导航到不同的页面。
女巫对象无所谓“被调用”,它总是导航到相同的页面。
只要我在“Invoke”方法中导航,导航就能正常工作。
它看起来像“PageAnimation_Completed”一直在同一个对象实例上调用,为什么?
这是关于堆栈和堆?如何解决这个问题?
我有以下类:
public class Action1 : TriggerAction<DependencyObject>
{
PhoneApplicationPage page;
protected override void OnAttached() {
...
page = (PhoneApplicationPage)elem;
...
}
[System.Windows.Interactivity.CustomPropertyValueEditorAttribute(System.Windows.Interactivity.CustomPropertyValueEditor.Storyboard)]
public Storyboard PageAnimation { get; set; }
public static readonly DependencyProperty Message = DependencyProperty.Register("IsSpinning", typeof(Uri), typeof(Action1), null);
public Uri Page
{
get { return (Uri)GetValue(Message); }
set { SetValue(Message, value); }
}
protected override void Invoke(object o)
{
PageAnimation.Completed += new EventHandler(PageAnimation_Completed);
PageAnimation.Begin();
}
void PageAnimation_Completed(object sender, EventArgs e)
{
page.NavigationService.Navigate(new Uri("/" + this.Page.OriginalString, UriKind.RelativeOrAbsolute));
PageAnimation.Stop();
}
}
答
你需要从PageAnimation.Completed
事件退订:
void PageAnimation_Completed(object sender, EventArgs e)
{
PageAnimation.Completed -= PageAnimation_Completed;
page.NavigationService.Navigate(new Uri("/" + this.Page.OriginalString, UriKind.RelativeOrAbsolute));
PageAnimation.Stop();
}
非常感谢你。这个问题我整天都失去了。 但是我仍然不明白这个问题 - 为什么它现在有效? – 2010-11-14 10:33:40
每次订阅事件时,处理程序都会有效*添加*,而不是*替换*。因此,每次调用Invoke时,都会将'PageAnimation_Completed'添加到处理程序列表中,所以每次事件触发时都会调用它,即使'Begin'是从另一个实例调用的(我假设在所有实例之间共享了“PageAnimation” ) – 2010-11-14 13:42:57