WPF RichTextBox不自动换行

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
{
    /// <summary>
    /// RichTextBox长度自动增长 扩展类
    /// </summary>
    public static class FlowDocumentExtensions
    {
        private static IEnumerable<TextElement> 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[] { });
                }
            }
        }

猜你喜欢

转载自www.cnblogs.com/xunyiHe/p/10538959.html
WPF