博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
WPF RichTextBox不自动换行
阅读量:6354 次
发布时间:2019-06-22

本文共 6760 字,大约阅读时间需要 22 分钟。

1、RichTextBox扩展类

using System;using System.Collections.Generic;using System.Globalization;using System.Linq;using System.Text;using System.Windows.Documents;using System.Windows.Media;namespace PrintTime{    ///     /// RichTextBox长度自动增长 扩展类    ///     public static class FlowDocumentExtensions    {        private static IEnumerable
GetRunsAndParagraphs(FlowDocument doc) { for (TextPointer position = doc.ContentStart; position != null && position.CompareTo(doc.ContentEnd) <= 0; position = position.GetNextContextPosition(LogicalDirection.Forward)) { if (position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd) { Run run = position.Parent as Run; if (run != null) { yield return run; } else { Paragraph para = position.Parent as Paragraph; if (para != null) { yield return para; } } } } } public static FormattedText GetFormattedText(this FlowDocument doc) { if (doc == null) { throw new ArgumentNullException("doc"); } //doc.PagePadding = new System.Windows.Thickness(0, 0, 0, 0);//设置文本的边距 FormattedText output = new FormattedText( GetText(doc), CultureInfo.CurrentCulture, doc.FlowDirection, new Typeface(doc.FontFamily, doc.FontStyle, doc.FontWeight, doc.FontStretch), doc.FontSize, doc.Foreground); int offset = 0; foreach (TextElement el in GetRunsAndParagraphs(doc)) { Run run = el as Run; if (run != null) { int count = run.Text.Length; output.SetFontFamily(run.FontFamily, offset, count); output.SetFontStyle(run.FontStyle, offset, count); output.SetFontWeight(run.FontWeight, offset, count); output.SetFontSize(run.FontSize, offset, count); output.SetForegroundBrush(run.Foreground, offset, count); output.SetFontStretch(run.FontStretch, offset, count); output.SetTextDecorations(run.TextDecorations, offset, count); offset += count; } else { offset += Environment.NewLine.Length; } } return output; } private static string GetText(FlowDocument doc) { StringBuilder sb = new StringBuilder(); foreach (TextElement el in GetRunsAndParagraphs(doc)) { Run run = el as Run; sb.Append(run == null ? Environment.NewLine : run.Text); } return sb.ToString(); } }}

2、RichTextBox控件定义

RichTextBox rtb = new RichTextBox()            {                Margin = new Thickness(5),                AllowDrop = true,                HorizontalAlignment = HorizontalAlignment.Left,                BorderThickness = new Thickness(1),                VerticalAlignment = VerticalAlignment.Top,                BorderBrush = Brushes.Transparent,                FontSize = model.FontSize,                //FontFamily = new FontFamily(cb_FontFamily.SelectedValue.ToString()),                FontFamily = new FontFamily(model.FontName),                Background = Brushes.Transparent,            };            string strName = "rtb_" + dateName;            if (textTpe.Equals("timeStamp"))            {                Thread.Sleep(1);                dateName = DateTime.Now.ToString("yyyyMMddHHmmss");                strName = "rtb_date_" + dateName + "_" + model.TimestampSelectIndex;                rtb.IsReadOnly = true;                gridWords.Tag = model.TimestampText== null ?  "": model.TimestampText;                rtb.Tag = model.TimestampFormat == null ? "" : model.TimestampFormat;            }            rtb.Name = strName;            rtb.Document = new FlowDocument() { LineHeight = 1 };//修改行间距            //rtb.TextChanged += new TextChangedEventHandler((o, q) => rtb.Width = rtb.Document.GetFormattedText().WidthIncludingTrailingWhitespace + 16);            rtb.VerticalScrollBarVisibility = ScrollBarVisibility.Disabled;            rtb.PreviewMouseLeftButtonDown += Rtb_PreviewMouseLeftButtonDown;            rtb.PreviewMouseRightButtonDown += Rtb_PreviewMouseRightButtonDown;            rtb.Loaded += Rtb_Loaded;            rtb.GotFocus += Rtb_GotFocus;            rtb.LostFocus += Rtb_LostFocus;            rtb.TextChanged += Rtb_TextChanged;            rtb.ContextMenu = (ContextMenu)this.FindResource("ContextMenu");                        gridWords.Children.Add(rtb);

3、事件处理

private string rtbLastText = "";        private void Rtb_TextChanged(object sender, TextChangedEventArgs e)        {            RichTextBox richTextBox = sender as RichTextBox;            if (richTextBox != null)            {                DockPanel dockPanel = richTextBox.Parent as DockPanel;                if (dockPanel != null)                {                    if (dockPanel.Width != double.NaN)                    {                        dockPanel.Width = double.NaN;                    }                    if (dockPanel.Height != double.NaN)                    {                        dockPanel.Height = double.NaN;                    }                }                if (System.Environment.OSVersion.Version.Major == 6 && System.Environment.OSVersion.Version.Minor == 1)//win7模板加粗文本最后一字换行问题                {                    richTextBox.Width = richTextBox.Document.GetFormattedText().WidthIncludingTrailingWhitespace + 18;                }                else                {                    richTextBox.Width = richTextBox.Document.GetFormattedText().WidthIncludingTrailingWhitespace + 16;                }                richTextBox.Document.LineHeight = 1;//处理复制粘贴后行高变为Nan问题                //richTextBox.Document.PagePadding = new Thickness(0);                TextRange a = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);                if (rtbLastText != a.Text.ToString() && !isUndo)                {                    rtbLastText = a.Text.ToString();                    CommandStack.AddUndo(richTextBox, CommandTypes.RichTextBoxEdit, new object[] { });                }            }        }

 

转载于:https://www.cnblogs.com/xunyiHe/p/10538959.html

你可能感兴趣的文章
IOS开发之新浪微博OAuth2
查看>>
maven的单元测试中没有
查看>>
python使用psutil获取服务器信息
查看>>
Fibonacci Numbers
查看>>
(HW)CoinsCombination(Java)
查看>>
table清除样式大全
查看>>
用Python做大批量请求发送
查看>>
HDU-1231,最大区间连续和总结-分治法-dp
查看>>
How to remove popup on boot on Windows 2003
查看>>
css之position相对定位和绝对定位
查看>>
「译」Java集合框架系列教程四:Set接口
查看>>
max number of clients reached Redis测试环境报错
查看>>
【Andorid开发框架学习】之Mina开发之服务器开发
查看>>
2.3.9 python 内置函数
查看>>
C#学习(八)之Stream
查看>>
POJ 1182
查看>>
格式化数字字符串 与C#变量
查看>>
二、Java面向对象(7)_封装思想——理解封装思想
查看>>
Android课程---Android ImageView的scaleType属性与adjustViewBounds属性(转)
查看>>
2018-2019-1 20165212 20165313 20165222 实验四 外设驱动程序设计
查看>>