UWP TextBox control giving unexpected results

不羁的心 提交于 2019-12-25 11:51:54

问题


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"));


来源:https://stackoverflow.com/questions/44339045/uwp-textbox-control-giving-unexpected-results

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!