C# 使用正则表达式并更新richtextbox wpf c中的文本#
我这里有我的代码:C# 使用正则表达式并更新richtextbox wpf c中的文本#,c#,regex,wpf,richtextbox,C#,Regex,Wpf,Richtextbox,我这里有我的代码: mainWindow.Dispatcher.Invoke(new Action(() => mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("Hello"))))); string myText = new TextRange(mainWindow.richtextbox2.Document.ContentStart
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run("Hello")))));
string myText = new TextRange(mainWindow.richtextbox2.Document.ContentStart, mainWindow.richtextbox2.Document.ContentEnd).Text;
//replace two or more consecutive spaces with a single space, and
//replace two or more consecutive newlines with a single newline.
var str = Regex.Replace(myText, @"( |\r?\n)\1+", "$1", RegexOptions.Multiline);
mainWindow.Dispatcher.Invoke(new Action(() =>
mainWindow.richtextbox2.Document.Blocks.Add(new Paragraph(new Run(str)))));
我知道Hello在第一次启动时是多余的。我想同时删除这个冗余,我还想删除每个文本行中的间距。这是我在3次跑步中拍摄的屏幕截图
我怎样才能解决这个问题?请修改代码
编辑:这是我更改richtextbox的XAML后的屏幕截图。我怎样才能从第一行开始呢
在xaml中试试这个(我制作了演示):
这可能是一种选择。。它会删除一些间距,但不确定是否要删除更多间距
<RichTextBox Name="richtextbox2" Height="100" BorderBrush="Black" BorderThickness="1">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>
我认为这个问题几乎已经解决了。我试过XAML,效果很好。与@Max Mazur的代码相同。但在第一次开始时,“Hello”文本显示在下一行中,我将在我的提问中更新我的图片。可以现在已经解决了。呵呵。我移除了这个按钮。非常感谢你的帮助。
mainWindow.Dispatcher.Invoke(new Action(() => DoSomething));
private void DoSomething(){
string myText = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd).Text;
var resultString = Regex.Replace(myText, @"( |\r?\n)\1+", "$1");
MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(resultString));
richTextBox.SelectAll();
richTextBox.Selection.Load(stream, DataFormats.Text);
}
<RichTextBox Name="richtextbox2" Height="100" BorderBrush="Black" BorderThickness="1">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>