简体   繁体   中英

The text of a file with OnFileActivated doesn't work C# UWP Xaml

In my app, I use the OnFileActivated for get when a file with the extension .txt is open with my app in "Open with" in File Explorer show the text of this txt file in the RichEditBox and show the path in the title of the app. The code for put the title is good because in the title put the Path of the file, but the code for show the text of the file doesn't work.

I was guided from this page: http://grogansoft.com/blog/?p=1197

The code in the App.xaml.cs:

protected override void OnFileActivated(FileActivatedEventArgs args)
    {
        base.OnFileActivated(args);
        var rootFrame = new Frame();
        rootFrame.Navigated += OnNavigatedTo;
        rootFrame.Navigate(typeof(MainPage), args);
        Window.Current.Content = rootFrame;
        Window.Current.Activate();
    }
async void OnNavigatedTo(object sender, NavigationEventArgs e)
    {
        var args = e.Parameter as Windows.ApplicationModel.Activation.IActivatedEventArgs;
        if (args != null)
        {
            if (args.Kind == Windows.ApplicationModel.Activation.ActivationKind.File)
            {
                var fileArgs = args as Windows.ApplicationModel.Activation.FileActivatedEventArgs;
                string strFilePath = fileArgs.Files[0].Path;
                var file = (StorageFile)fileArgs.Files[0];
                await new MainPage().LoadTextFile(file);
            }
        }    
    }

The function for show the text in the RichEditBox

public async Task LoadTextFile(StorageFile file)
    {
            string text = await FileIO.ReadTextAsync(file);    
            current_path = file.Path;
            current_file = file.Name;
            var appView = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView();
            appView.Title = current_path;
            RichEditBox1.Document.SetText(TextSetOptions.None, text);
    }

There are two basic problems here:

  1. You should use the OnNavigatedTo virtual method in MainPage itself, rather than using the Navigated event on the Frame .
  2. You don't need to construct a fresh copy of MainPage -- the navigation service will do that for you. Just call the LoadTextFile method from within the OnNavigatedTo method.

Like this:

// In MainPage.xaml.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
  // Your code here...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM