首页 > 解决方案 > 暂停或关闭应用程序时从 TextBox 写入 .txt 文件

问题描述

有一个TextBox用户可以输入一些数据的地方。当应用程序关闭时(通过单击窗口右上角的 X 按钮),应用程序需要TextBox在关闭应用程序之前将输入的内容保存到 .txt 文件中。

这是我在App.xaml.cs文件中的代码。

private async void OnSuspending(object sender, SuspendingEventArgs e)
{
    var deferral = e.SuspendingOperation.GetDeferral();
    //TODO: Save application state and stop any background activity
    await WriteTextToFile();

    deferral.Complete();
}

private async Task WriteTextToFile()
{
    try
    {
        string text = textBox.Text;
        StorageFile textFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///TextFile1.txt"));
        await FileIO.WriteTextAsync(textFile, text);
    }
    catch
    {

    }
}

我在try块中的 textBox 下得到一个红色下划线。

它说,

当前上下文中不存在名称“textBox”

我猜不可能从文件中访问TextBox控件。App.xaml.cs

标签: c#uwp

解决方案


在 App.xaml.cs 中

    private MainPage mainFrame;
    protected override void OnLaunched(LaunchActivatedEventArgs e)
    {
        Frame rootFrame = Window.Current.Content as Frame;
        if (rootFrame == null)
        {
            rootFrame = new Frame();
            rootFrame.NavigationFailed += OnNavigationFailed;
            if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                //TODO: Load state from previously suspended application
            }
            Window.Current.Content = rootFrame;
        }

        if (e.PrelaunchActivated == false)
        {
            if (rootFrame.Content == null)
            {
                rootFrame.Navigate(typeof(MainPage), e.Arguments);
                mainFrame = (MainPage) rootFrame.Content; //*
            }
            Window.Current.Activate();
        }
    }

    private void OnSuspending(object sender, SuspendingEventArgs e)
    {
        var deferral = e.SuspendingOperation.GetDeferral();
        string text = mainFrame.Main_TextBox.Text;
        string text2 = MainPage.rootPage.Main_TextBox.Text;
        Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("hello.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
        await Windows.Storage.FileIO.WriteTextAsync(sampleFile , text);
        deferral.Complete();
    }

在 Main.xaml.cs 中(TextBox_1 => xaml 文件中 TextBox 的名称)

public sealed partial class MainPage : Page
{
    public TextBox Main_TextBox => TextBox_1; //*
    public static MainPage rootPage; //*
    public MainPage()
    {
        this.InitializeComponent();
        if (rootPage == null)
        {
            rootPage = this;
        }
    }

}

如果主框架中的文本框,您可以使用 App.xaml.cs 中的 rootFrame 访问。您可以通过其他方式在页面中创建静态变量,然后您可以使用任何属性访问

编辑:你可以看到你的文件C:\Users\{UserName}\AppData\Local\Packages\{PackageName}\LocalState\hello.txt


推荐阅读