c# - 暂停或关闭应用程序时从 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
解决方案
在 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
推荐阅读
- python - 如何解决在 python3.7 中安装 pycsv 的错误?
- reactjs - 只有当它等于 action.id 时,如何告诉 redux 设置某个值
- c# - 有没有更好的方法来使 asp.net mvc 应用程序中使用的 redis 缓存失效?
- java - Java 类定义的类型推断失败。我该如何解决这个问题?
- jquery - 检索添加到密钥的随机数的本地存储项
- mysql - 从字段中提取日期
- python - 如何从 python 返回的 json 文件中获取某个密钥?
- r - 突出显示 R 中最佳拟合模型的预测线?
- c# - 如何使用 Outlook 桌面 (Office 365) 的 VSTO 加载项显示或隐藏 Outlook 信息栏
- dart - 如何将 Multi Image Picker 与 Image Cropper 一起使用