UWP TextBox control giving unexpected results

2019-09-15 07:00发布

问题:

Simple Text Editor

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();
        }
    }

回答1:

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.

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

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


标签: c# textbox uwp