WPF里给RichTextBox中的文本添加行号

Posted on 2011-04-07 17:36  6哒忆夏  阅读(2422)  评论(2编辑  收藏  举报

     这是一个简单的DEMO,关键是DEMO添加行的思路,首先给RichTextBox添加6行文本,然后点击添加行按钮后,将每行文本取出,添加行号,最后将添加完行号的内容重新填充进RichTextBox里。

第一步:新建一个WPF应用程序

第二步:界面代码:

界面代码
<Window x:Class="WpfApplication4.MainWindow"
xmlns
="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x
="http://schemas.microsoft.com/winfx/2006/xaml"
Title
="MainWindow" Height="350" Width="525" Topmost="True">
<Grid Name="grid">
<RichTextBox Name="rtb" AcceptsReturn="True" Width="200" Height="200" AcceptsTab="True" VerticalScrollBarVisibility="Auto"/>
<Button Name="btn" Margin="371,228,46,55" Content="添加行号" Click="btn_Click"></Button>
</Grid>
</Window>

第三步:后台代码

后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication4
{
///<summary>
/// MainWindow.xaml 的交互逻辑
///</summary>
publicpartialclass MainWindow : Window
{

public MainWindow()
{
InitializeComponent();
//添加文本
FlowDocument flowDoc =new FlowDocument();
flowDoc.Blocks.Add(
new Paragraph(new Run("Line 1")));
flowDoc.Blocks.Add(
new Paragraph(new Run("Line 2")));
flowDoc.Blocks.Add(
new Paragraph(new Run("Line 3")));
flowDoc.Blocks.Add(
new Paragraph(new Run("Line 4")));
flowDoc.Blocks.Add(
new Paragraph(new Run("Line 5")));
flowDoc.Blocks.Add(
new Paragraph(new Run("Line 6")));
flowDoc.Blocks.Add(
new Paragraph(new Run("Line 7")));
flowDoc.Blocks.Add(
new Paragraph(new Run("Line 8")));
rtb.Document
= flowDoc;

}

privatevoid btn_Click(object sender, RoutedEventArgs e)
{
List
<Paragraph> list =new List<Paragraph>();
List
<Block> bc = rtb.Document.Blocks.ToList();
int i =1;
for (int j =0; j < bc.Count; j++)
{

Paragraph p
= bc[j] as Paragraph;
Run r
=new Run();
foreach (Inline item1 in p.Inlines)
{
r.Text
= i +" : "+ ((Run)item1).Text; //给每行文本加上行号
}
p.Inlines.Clear();
p.Inlines.Add(r);
list.Add(p);
i
++;
}

FlowDocument flowDoc1
=new FlowDocument();
foreach (Paragraph item in list)
{
flowDoc1.Blocks.Add(item);
}

rtb.Document
= flowDoc1;
btn.Visibility
= Visibility.Collapsed;
}

}
}

Copyright © 2024 6哒忆夏
Powered by .NET 8.0 on Kubernetes