WPF RichTextBox 使用示例


一、取出RichTextBox值

1、取得RichTextBox 文字

TextRange documentTextRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
string text = DataFormats.Text;

2、取得RichTextBox內的XAML文檔

string xaml = System.Windows.Markup.XamlWriter.Save(richTextBox.Document);

3、將richTextBox的類容以二進制數據的方法取出
     FlowDocument document = richTextBox.Document;
     System.IO.Stream s = new System.IO.MemoryStream(); 
     System.Windows.Markup.XamlWriter.Save(document, s);         
     byte[] data = new byte[s.Length];
     s.Position = 0;
     s.Read(data, 0, data.Length);
      s.Close();

二、給RichTextBox賦值

String字符串賦值給RichTextBox

FlowDocument doc = new FlowDocument();
Paragraph p = new Paragraph(); // Paragraph 類似於 html 的 P 標簽
Run r = new Run("文字"); // Run 是一個 Inline 的標簽
p.Inlines.Add(r);
doc.Blocks.Add(p);
richTextBox.Document = doc;

以上可以簡化為

richTextBox.Document = new FlowDocument(new Paragraph(new Run("文字")));

 

第一種方法:將XAML字符串轉換為數據流賦值給richTextBox中 
  System.IO.StringReader sr = new System.IO.StringReader(xw);
  System.Xml.XmlReader xr = System.Xml.XmlReader.Create(sr);
  richTextBox1.Document = (FlowDocument)System.Windows.Markup.XamlReader.Load(xr);

第二種方法:將Text字符串轉換為數據流賦值給richTextBox中 

using (StreamReader streamReader = File.OpenText(filename)) {
           Paragraph paragraph = new Paragraph();
           paragraph.Text = streamReader.ReadToEnd();
           richTextBox.Document.Blocks.Add(paragraph);
 }

第三種方法:將二進制數據賦值給richTextBox
   System.IO.Stream ss = new System.IO.MemoryStream(data);
    FlowDocument doc = System.Windows.Markup.XamlReader.Load(ss) as FlowDocument;
     ss.Close();
     richTextBox1.Document = doc;

三、清空RichTextBox的方法

System.Windows.Documents.FlowDocument doc = richTextBox.Document;
doc.Blocks.Clear();

 

四、復制, 剪切,粘貼,全選

方法一:將鍵擊發送到應用程序的方法
richTextBox.Focus();
SendKeys.Send("^a");//全選
SendKeys.Send("^c");//復制
SendKeys.Send("^x");//剪切
SendKeys.Send("^v");//粘貼

方法二:直接通過命令操作

<RichTextBox Name="richTextBox" Height="200" IsEnabled="True">
<RichTextBox.ContextMenu>
<ContextMenu>
<MenuItem Header="復制" Command="ApplicationCommands.Copy" />
<MenuItem Header="粘貼" Command="ApplicationCommands.Paste" />
<MenuItem Header="剪切" Command="ApplicationCommands.Cut" />
</ContextMenu>
</RichTextBox.ContextMenu>
</RichTextBox>

五、RichTextBox增加XAML內容

<RichTextBox Name="richTextBox" Height="200" IsEnabled="True">
<FlowDocument>
<Paragraph>
<Bold>Bold</Bold>
<Italic>Italicize</Italic>
<Hyperlink>Hyperlink stuff</Hyperlink>
</Paragraph>
</FlowDocument>
</RichTextBox>

六、 RichTextBox 設置Style內容樣式,如:縮短段間距

<RichTextBox Name="richTextBox" Height="200" IsEnabled="True">
<RichTextBox.Resources>
<Style TargetType="{x:Type Paragraph}">
<Setter Property="Margin" Value="0"/>
</Style>
</RichTextBox.Resources>
</RichTextBox>

七、RichTextBox插入圖片,點擊按鈕選取圖片

Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.Filter = "Text Files (*.jpg; *.png; *.gif)|*.jpg;*.png;*.gif";
ofd.Multiselect = false;
if (ofd.ShowDialog() == true)
{
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
BitmapImage bImg = new BitmapImage();
bImg.BeginInit();
//bImg.UriSource = new Uri(@"C:\Users\admin\source\repos\WPFRichTextBox\WPFRichTextBox\ext_apk.png", UriKind.Relative);
bImg.UriSource = new Uri(ofd.FileName, UriKind.RelativeOrAbsolute);
bImg.EndInit();
img.Source = bImg;
//調整圖片大小
if (bImg.Height > 100 || bImg.Width > 100)
{
img.Height = bImg.Height * 0.2;
img.Width = bImg.Width * 0.2;
}
//圖片縮放模式
//img.Stretch = Stretch.Uniform;
new InlineUIContainer(img, richTextBox.Selection.Start); //插入圖片到選定位置
}

八、查找段落 Paragraph

var doc = this.richTextBox.Document;
var blocks = doc.Blocks.ToArray();
var paragraphs = blocks.Where(b => b is Paragraph).ToArray();
Paragraph paragraph = (Paragraph)paragraphs[0];

//修改段落內容
p.Inlines.Clear();
p.Inlines.Add(new Run("天涯共此時"));

九、查找FlowDocument中的所有圖像

1、查找Paragraph中的所有圖像

List<System.Windows.Controls.Image> FindAllImagesInParagraph(Paragraph paragraph)
{
List<System.Windows.Controls.Image> result = null;
foreach (var inline in paragraph.Inlines)
{
var inlineUIContainer = inline as InlineUIContainer;
if (inlineUIContainer != null)
{
var image = inlineUIContainer.Child as System.Windows.Controls.Image;
if (image != null)
{
if (result == null)
result = new List<System.Windows.Controls.Image>();
result.Add(image);
}
}
}
return result;
}

十、RichTextBox 啟用 WPF 控件

默認情況下,RichTextBox 禁用處理 Button Click,ContextMenu 等

1、實現步驟,重寫 FlowDocument

public class TalkFlowDocument : FlowDocument
{
    protected override bool IsEnabledCore
    {
        get
        {
            return true;
        }
    }
}

2、XAML 引用

<Window xmlns:local="clr-namespace:HitoolCore">
    <Grid>
        <RichTextBox IsReadOnly="True">
            <local:TalkFlowDocument>
                <Paragraph>
                    <TextBlock Text="你好"/>
                    <Paragraph.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="復制" />
                            <MenuItem Header="引用" />
                        </ContextMenu>
                    </Paragraph.ContextMenu>
                </Paragraph>
                <Paragraph>
                    <TextBlock Text="以后請多關照"/>
                    <Paragraph.ContextMenu>
                        <ContextMenu>
                            <MenuItem Header="撤回" />
                            <MenuItem Header="轉發" />
                        </ContextMenu>
                    </Paragraph.ContextMenu>
                </Paragraph>
            </local:TalkFlowDocument>
        </RichTextBox>
    </Grid>
</Window>

  

參考:http://www.voidcn.com/article/p-vrncotwa-bxx.html

 

WPF RichTextBox的使用總結

https://www.cnblogs.com/gaobing/p/3865254.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM