简体   繁体   中英

How to work with RichTextBox in WPF

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 (eg 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.

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 .

我可以使用此页面上提供的代码解决问题: http : //www.codeproject.com/Articles/37169/WPF-RichText-Editor

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM