Search code examples
c#xamlwindows-runtimestoragefile

Passing a StorageFile to OnNavigatedTo in a C# WinRT app


In my C# WinRT app, I would like to pass a StorageFile to a new navigation page inside a frame so that the page can open the document and put the file's contents into a RichEditBox. I've tried to add an optional parameter to OnNavigatedTo with a StorageFile, but it causes the app to crash.

I tried to make it so that I can navigate to the page like this from another page that contains a frame:

RootFrame.Navigate(typeof(Editor), file);

And launch the framed page like so:

protected override async void OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs e, Windows.Storage.StorageFile file)
        {
            if (file)
            {
                try
                {
                    EditorBox.Document.SetText(Windows.UI.Text.TextSetOptions.None, await Windows.Storage.FileIO.ReadTextAsync(file));
                }
                catch
                {
                }
            }
        }

But doing this, I get the following errors:

  • 'TestApp.Page3.OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs, Windows.Storage.StorageFile)' is a new virtual member in sealed class 'TestApp.Page3'
  • 'TestApp.Page3.OnNavigatedTo(Windows.UI.Xaml.Navigation.NavigationEventArgs, Windows.Storage.StorageFile)': no suitable method found to override

Is there any way to do something similar to what I am trying to accomplish?


Solution

  • You can only override existing methods. You can't override what doesn't exist - you'd create something new instead. However Windows wouldn't call a method it doesn't know. So stick with what Windows has to offer:

    protected override async void OnNavigatedTo(NavigationEventArgs e)
    {
        var file = e.Parameter as Windows.Storage.StorageFile;
        if (file!=null)
        {
            ...
        }
    }