This is a text editor. I am trying to open a new file and if the existing file is not empty, users get a warning to save the file or not. But if I use the condition if (text== "")
, the value of text still has "\r\n"
new line value. Even I didn't click on the text area.
Why does string get the value of the new line? It doesn't have to be empty?
private void New_Click(object sender, RoutedEventArgs e)
{
var text = new TextRange(richtxtbox.Document.ContentStart, richtxtbox.Document.ContentEnd).Text;
if (text == "")
{
MainWindow newWindow = new MainWindow();
newWindow.Show();
Window.GetWindow(this).Close();
}
else
{
// ...
}
}
I have to do this:
if (text == "" || text == "\r\n")
{
MainWindow newWindow = new MainWindow();
newWindow.Show();
Window.GetWindow(this).Close();
}
CodePudding user response:
You wrote:
I am trying to open a new file and if the existing file is not empty...
What do you mean "the existing file is not empty"? I guess you mean the current content of the RichtextBox
, that actually is container for the FlowDocument
object. Right?
Result of the var text = new TextRange(richtxtbox.Document.ContentStart, richtxtbox.Document.ContentEnd).Text
depend on content of the FlowDocument
.
If you declare RichTextBox
as below than text
will contain "\r\n"
. It's because the FlowDocument
will contain one Paragraph
block. And when this paragraph is converted to text it will automatically appended with the Environment.NewLine
.
<RichTextBox Name="richtxtbox">
<FlowDocument>
<Paragraph>
</Paragraph>
</FlowDocument>
</RichTextBox>
But if you declare RichTextBox
as empty FlowDocument
than text
will be empty - it contains 0
blocks.
<RichTextBox Name="richtxtbox">
<FlowDocument>
</FlowDocument>
</RichTextBox>
For more information read the following article: RichTextBox Overview