C# UWP在基页中添加事件处理程序导致AccessViolationException

C# UWP在基页中添加事件处理程序导致AccessViolationException,c#,xaml,uwp,C#,Xaml,Uwp,我有“BasePage”类,它是我项目中所有其他页面的基类。 在初始化过程中,我为事件“BackRequest”添加了“SystemNavigationManager”的EventHandler。由于某些原因,当XAML设计器试图呈现扩展“BasePage”的类的XAML时,行id导致“AccessViolationException” 我不熟悉UWP,所以我非常感谢你给我的提示 基本页面 public class BasePage: Page { internal string tit

我有“BasePage”类,它是我项目中所有其他页面的基类。 在初始化过程中,我为事件“BackRequest”添加了“SystemNavigationManager”的EventHandler。由于某些原因,当XAML设计器试图呈现扩展“BasePage”的类的XAML时,行id导致“AccessViolationException”

我不熟悉UWP,所以我非常感谢你给我的提示

基本页面

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();
    }
}
解决方案 正如伊万所说,最终的代码是这样的。没有一丝虫子的痕迹

基本页面

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

您不应该订阅构造函数上的back事件,而应该订阅
OnNavigatedTo
并在
OnNavigatedFrom
中取消订阅。即使它没有崩溃,也会导致很多问题,因为当您按下“后退”按钮时,您的后退逻辑将在之前的所有页面上被激活。

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

这听起来更符合逻辑。我试试看。这听起来更符合逻辑。我试试看。