RichTextBox Binding is broken when text is manually modified or cleared

后端 未结 2 1762
我寻月下人不归
我寻月下人不归 2021-01-28 00:30

I have a RichTextBox bound to a string.

Using C# I generate a string that writes to it.

But if I want to manually change the text by clicking into t

相关标签:
2条回答
  • 2021-01-28 01:08

    When you edit the RichTextBox, you alter the elements inside of the FlowDocument element. The element you have a binding on, is probably removed at some point during this editing. Have a look at RichtTextBox.Document.Groups to see what's happening when you edit the RichTextBox.

    The default RichTextBox does not really support MVVM/Binding very well. You'd want to have a binding on the Document property, but this is not supported for the default RichTextBox. You could have a look here.

    Or extend it yourself, something like this?:

    BindableRichTextBox class

    public class BindableRichTextBox : RichTextBox
    {
        public static readonly DependencyProperty DocumentProperty = DependencyProperty.Register(nameof(Document), typeof(FlowDocument), typeof(BindableRichTextBox), new FrameworkPropertyMetadata(null, OnDocumentChanged));
    
        public new FlowDocument Document
        {
            get => (FlowDocument)GetValue(DocumentProperty);
            set => SetValue(DocumentProperty, value);
        }
    
        public static void OnDocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var rtb = (RichTextBox)obj;
            rtb.Document = args.NewValue != null ? (FlowDocument)args.NewValue : new FlowDocument();
        }   
    }
    

    XAML

    <controls:BindableRichTextBox Document="{Binding YourFlowDocumentObject, Mode=OneWay}"/>
    

    Then you can get the string from the FlowDocument.

    0 讨论(0)
  • 2021-01-28 01:29

    Why you have to write this line. Please remove line after check.

    if (_ScriptView_Text == value)
    {
       return;
    }
    
    0 讨论(0)
提交回复
热议问题