问题
I have a WPF application in which I want to convert a TextBox into a RichTextBox. I have already written the following lines of code:
<RichTextBox>
<FlowDocument>
<Paragraph>
<Run Text="{Binding GeneralDescription}" />
</Paragraph>
</FlowDocument>
</RichTextBox>
This has the effect that the string GeneralDescription is displayed and I can edit and format it. Now I have the problem that when I mark a part of the text, format it (e.g. make it bold), save the document and re-open the document, only the part of the text until the formatting is displayed. I am not sure if the error lies within the display or within the saving. In either case it's annoying. How can I make it work? Is it a problem that GeneralDescription is of type string?
Thanks in advance.
回答1:
The Problem is that your string
data contains only plain text and your XAML design tags
in it will be ignored at loading.
Textbox
and RichTextBox
are controls with a complete different behavior.
The problem also is that RichTextBox
don't support this kind of binding native. A Document on a RichTextBox
is not a dependency property, that's why.
Personally i use David Veeneman extended control for cases like this.
For Saving or Loading a FlowDocument
directly use:
FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite);
XamlWriter.Save(myFlowDocumentObject, fs);
and
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
FlowDocument myFlowDocumentObject = XamlReader.Load(fs) as FlowDocument;
By the way, the Run
Tag data binding is partially supported.
One way data binding is fully supported. A Run can be bound to a data source and the content of the Run will reflect the value of what it is bound to. The bound Run will receive and display any changes that occur in the data source.
Two way data binding is partially supported. If a bound Run is updated via calls to the WPF property system, the data source which the Run is bound to will reflect the changes to the Run. On the other hand, if a bound Run is updated via a RichTextBox or the text object model, the Run will lose its binding.
回答2:
I was able to solve the problem with the code provided at this page: http://www.codeproject.com/Articles/37169/WPF-RichText-Editor
来源:https://stackoverflow.com/questions/36303258/how-to-work-with-richtextbox-in-wpf