在基页中添加事件处理程序会导致AccessViolationException

本文关键字:AccessViolationException 程序 事件处理 基页 添加 | 更新日期: 2023-09-27 18:09:44

我有'BasePage'类,这是我项目中所有其他页面的基类。在初始化中,我为事件'BackRequest'为'SystemNavigationManager'添加eventandler。由于某些原因,行id导致'AccessViolationException'当XAML设计器试图渲染XAML类扩展'BasePage'

我不熟悉UWP,所以我将非常感谢你的建议。

BasePage

public class BasePage: Page {
    internal string title = "";
    internal HeaderView headerView;
    public BasePage() {
        this.Loaded += BasePage_Loaded;
        // FIXME: For some reason if this line is uncommented then xaml designer fails. 
        SystemNavigationManager.GetForCurrentView().BackRequested += BasePage_BackRequested;
    }
    private void BasePage_BackRequested(object sender, BackRequestedEventArgs e) {
        bool handled = e.Handled;
        this.BackRequested(ref handled);
        e.Handled = handled;
    }
    private void BackRequested(ref bool handled) {
        //Get a hold of the current frame so that we can inspect the app back stack.
        if (this.Frame == null)
            return;
        // Check to see if this is the top-most page on the app back stack.
        if (this.Frame.CanGoBack && !handled) {
            // If not, set the event to handled and go back to the previous page in the app.
            handled = true;
            this.Frame.GoBack();
        }
    }
    private void setupPageAnimation() {
        TransitionCollection collection = new TransitionCollection();
        NavigationThemeTransition theme = new NavigationThemeTransition();
        var info = new ContinuumNavigationTransitionInfo();
        theme.DefaultNavigationTransitionInfo = info;
        collection.Add(theme);
        this.Transitions = collection;
    }
    private void BasePage_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) {
        setupPageAnimation();
    }
}

解决方案

就像Ivan说的,最终代码是这样的。没有任何错误的痕迹

BasePage

public BasePage() {
    this.Loaded += BasePage_Loaded;
}
protected override void OnNavigatedTo(NavigationEventArgs e) {
    base.OnNavigatedTo(e);
    SystemNavigationManager.GetForCurrentView().BackRequested += BasePage_BackRequested;
}
protected override void OnNavigatedFrom(NavigationEventArgs e) {
    base.OnNavigatedFrom(e);
    SystemNavigationManager.GetForCurrentView().BackRequested -= BasePage_BackRequested;
}

在基页中添加事件处理程序会导致AccessViolationException

您不应该在构造函数上订阅回事件,但在OnNavigatedToOnNavigatedFrom中取消订阅。即使它没有崩溃,它也会导致很多问题,因为当你按下后退按钮时,后退逻辑会在所有以前的页面上被激活。