向RichTextBox添加新行无效

问题描述 投票:0回答:1

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

这就是我对XAML的看法:

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

这就是我对Text属性的看法:

 private string emailBody;

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

现在,在我的ViewModel类中,我正在尝试向Property添加一个新行:

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;
        }

这不起作用。知道我在这里做错了吗?

c# wpf mvvm richtextbox
1个回答
0
投票

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

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

value += System.Environment.NewLine;

我希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.