向RichTextBox添加新行不起作用

时间:2019-02-13 17:48:36

标签: c# wpf mvvm richtextbox

我的WPF应用程序中有一个RichTextBox控件。我将RichTextBox的文本绑定到一个属性。我正在尝试在文本中添加新行,但无法正常工作。我尝试添加“ \ n”,“ Environment.NewLine”。这些都不起作用。

这就是XAML的用途:

  <RichTextBox Name="EmailBody" resources:HtmlRichTextBoxBehavior.Text="{Binding EmailBody}" IsDocumentEnabled="True" AcceptsTab="True"  ScrollViewer.VerticalScrollBarVisibility="Auto" SpellCheck.IsEnabled="True"/>

这就是我的文本属性:

 private string emailBody;

    public string EmailBody
    {
        get { return emailBody; }
        set
        {
            if (value != emailBody)
            {
                emailBody = value;
                OnPropertyChanged("EmailBody");
            }
        }
    }

现在,在我的ViewModel类中,我正在尝试向属性添加新行:

EmailBody += Environment.NewLine;

这是HtmlRichTextBoxBehavior的行为类:

      public class HtmlRichTextBoxBehavior : ObservableObject
    {
        public static readonly DependencyProperty TextProperty =
   DependencyProperty.RegisterAttached("Text", typeof(string),
   typeof(HtmlRichTextBoxBehavior), new UIPropertyMetadata(null, OnValueChanged));

        public static string GetText(RichTextBox o) { return (string)o.GetValue(TextProperty); }

        public static void SetText(RichTextBox o, string value) { o.SetValue(TextProperty, value); }

        private static void OnValueChanged(DependencyObject dependencyObject,
          DependencyPropertyChangedEventArgs e)
        {
            var richTextBox = (RichTextBox)dependencyObject;
            var text = (e.NewValue ?? string.Empty).ToString();
            var xaml = HtmlToXamlConverter.ConvertHtmlToXaml(text, true);
            var flowDocument = XamlReader.Parse(xaml) as FlowDocument;
            HyperlinksSubscriptions(flowDocument);
            richTextBox.Document = flowDocument;
        }

        private static void HyperlinksSubscriptions(FlowDocument flowDocument)
        {
            if (flowDocument == null) return;
            GetVisualChildren(flowDocument).OfType<Hyperlink>().ToList()
                     .ForEach(i => i.RequestNavigate += HyperlinkNavigate);
        }

        private static IEnumerable<DependencyObject> GetVisualChildren(DependencyObject root)
        {
            foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
            {
                yield return child;
                foreach (var descendants in GetVisualChildren(child)) yield return descendants;
            }
        }

        private static void HyperlinkNavigate(object sender,
         System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
            e.Handled = true;
        }

这不起作用。知道我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

我将尝试在设置为emailBody的值的末尾追加新行文本,而不是尝试将其分配给EmailBody。

您应该能够使用尝试使用的相同方法

value += System.Environment.NewLine;

我希望这对您有帮助