UWP TextBox 控件给出意外结果 [英] UWP TextBox control giving unexpected results

查看:20
本文介绍了UWP TextBox 控件给出意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

简单文本编辑器

选中 TextBox AcceptsReturn 属性后,将文本框的多行内容保存到文本文件会导致所有文本仅在记事本中打开时以单行书写.在 UWP TextBox 控件中加载文件时,它可以正常打开.旧的 WPF TextBox 控件没有这个问题.

With TextBox AcceptsReturn property checked saving multiline contents of a text box to a text file results all text written in single line only when opened in notepad. It opens fine when file is loaded in UWP TextBox control. I don't have this problem with old WPF TextBox control.

我的程序有两个按钮,打开和保存.中间是文本框.

My program has two buttons, open and save. In between there is text box.

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Popups;
using Windows.Storage.Pickers;
using Windows.Storage;

// ...
    StorageFile selectedFile;

    private async void openFileButton_Click(object sender, RoutedEventArgs e)
    {
        contentsTextBox.Text = string.Empty;
        addressText.Text = string.Empty;
        selectedFile = null;

        FileOpenPicker openDialog = new FileOpenPicker();
        openDialog.FileTypeFilter.Add("*");

        selectedFile = await openDialog.PickSingleFileAsync();
        if (selectedFile != null)
        {
            addressText.Text = selectedFile.Path;

            try
            {
                contentsTextBox.Text = await FileIO.ReadTextAsync(selectedFile);
            }

            catch (ArgumentOutOfRangeException) { } // In case file is empty
        }
    }

    private async void saveFileButton_Click(object sender, RoutedEventArgs e)
    {
        if (selectedFile != null)
        {
            await FileIO.WriteTextAsync(selectedFile, contentsTextBox.Text);
            await new MessageDialog("Changes saved!").ShowAsync();
        }
    }

推荐答案

在 TextBox 的 Text 属性中,行尾由 \r 表示.但是,记事本需要 \r\n 换行.

In the TextBox's Text property, an end-of-line is represented by \r. However, notepad expects \r\n for a line break.

有关两者(以及其他变体)之间差异的更多信息,请查看此内容.

For more information on the differences between the two (and other variants), see this.

在将文本保存到文件之前,只需将\r"替换为\r\n"即可.

Just replace "\r" to "\r\n" before saving the text to file.

await FileIO.WriteTextAsync(selectedFile, contentsTextBox.Text.Replace("\r", "\r\n"));

这篇关于UWP TextBox 控件给出意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆