Serializing WPF RichTextBox to XAML vs RTF - wpf

I have a RichTextBox and need to serialize its content to my database purely for storage purposes. It would appear that I have a choice between serializing as XAML or as RTF, and am wondering if there are any advantages to serializing to XAML over RTF, which I would consider as more "standard".
In particular, am I losing any capability by serializing to RTF instead of XAML? I understand XAML supports custom classes inside the FlowDocument, but I'm not currently using any custom classes (though the potential for extensibility might be enough reason to use XAML).
Update: I ended up going with RTF because of its support for text-encoded embedded images. XAML doesn't seem to include image data in its encoding, and XamlPackage encodes to binary, so RTF just works better for me. So far I haven't noticed any lack in capability.

If all your users are doing is typing in the RichTextBox and doing character formatting, RTF is as good as XAML. However there are many FlowDocument capabilities you may expose in your UI that are not convertible to RTF.
Here are some examples of FlowDocument (and RichTextBox) features that are not expressable in RTF or are implemented differently:
A Block can have an arbitrary BorderBrush, including gradient brushes with stops, VisualBrush
A Section has the HasTrailingParagraphBreakOnPaste property
Floater / ClearFloaters is implemented differently
Hyphenation can be enabled/disabled per block, not just per paragraph
WPF Styles and ResourceDictionaries can be included in the Resources property
Arbitrary WPF UI such as bound CheckBoxes, etc, can be embedded inside the RichTextBox and can be cut-and-pasted from other windows.
For example, suppose you want to allow users to drag or cut/paste in a "current date/time" field into your RichTextBox that would always show the current date and time. This could be done by adding a second read-only RichTextBox that has the InlineUIContainer and the already-bound control. This even works when cutting and pasting from other applications and does not require custom controls.
Another consideration is that the code to convert between FlowDocument and RTF is relatively complex so it may have lower performance than going with XAML. Of course loose XAML doesn't include images and such - for that you need to use XamlPackage. I store my XamlPackage in the database as a byte[], but you can also choose to Base64 encode it for storage as a string.
The bottom line is that it really depends on whether you want the user to be able to use features not available in RTF. Even if your application doesn't include tools to generate FlowDocuments that use these features, it is possible to cut-and-paste them from other applications.

Be aware that in Wpf RichTextBox's method called TextRange.Save has a bug whereby it loses any end of line terminator. Microsoft will not fix.
https://connect.microsoft.com/WPF/feedback/ViewFeedback.aspx?FeedbackID=478640&wa=wsignin1.0#tabs

Related

Is there a FlowDocument text processor control?

I need to make a sort of text processor. It must have these features:
All the WordPad features + paragraph styles like MS Word + text
columns + Zoom.
Insertion of tables, images, and controls like buttons, checkboxes.
Text search and replacement, spell check.
Syntax coloring, like code or quote parts on the StackOverflow site.
Ability to move text paragraph on custom places via mouse (like OneNote)
Ability to add some simple diagram (hierarchic)
I found on the web that the best way to implement the above requirements is to use FlowDocument. I also found that WPF RichTextControl would have many required functionalities, but on StackOverflow it is written that it has bad performance.
So, does it exist a FlowDocument text processor control?
If not, from which control could I start in order to implement the above requirements?

Multi-Language resources for wpf user control

I am building a wpf user control to provide navigation facilities for database records.
The control is provided with a set of default images (as illustrated above) which the end user can change is they so wish. In addition the end user can choose to dispense with images altogether. In the event that they select that option (for either one or all of the buttons that comprise the control) I have provided some default fallback text.
This text can also be overwritten by the end user if they so wish, but the default text at least provides them with some basic text that essentially conveys what the button does and saves them having to add text every time they use the control (default tooltip text is also provided).
Now if you happen to speak English, or your intended target audience is English this should work, but it doesn't really cater as is for languages other than English. This I would now like to change.
What reading I've done on the subject of multi-lingual resources and wpf seems to assume that one is talking about the overall application rather than a standalone user control that might be used in different language environments.
I had a talk with a creator of controls who said that making this multilingual would probably involve building several copies of the control for each intended language.
In the light of this I have two questions. Was the gentleman I spoke to correct, should I in fact build multiple copies of this for each language, of is there a way to have multi-language resources within the same copy of the user control?
If the latter is possible what is the correct way to go about achieving this. We will be dealing in total with default texts for eleven buttons (which I will need to be able to refer to in code within the control incidentally) and default texts for thirteen tooltips (which again will need to be able to be referred to within the code of the control).
Take a look on WPF localization extension.
Here's a pretty good documentation for it: link.
You can define your controls' localizable properties, which store their localized values in the satellite resource assemblies.
In your xaml code, define the localized properties with xaml extensions syntax:
<Button Content="{lex:Loc Test}" />
Then, create resource files for each culture your application will support and give them the same name as the main assembly plus the general or specific culture code (e.g. en-US, de, de-AT, ...) before the .resx ending yielding: AssemblyName.CultureCode.resx.
Now, populate the resource files with your localized properties key/value pairs and build the project.
You're done!

Can not get image information from Silverlight RichTextEditor

I'm trying to use the Silverlight RichTextEditor in our website. Now we'd like to translate the content in richtextbox into HTML code to save and load.
However, as we know, the richtextbox control does not support the UIelements output. When we insert an image in the richtextbox, the richtextbox would use a inlineUIcontainer to show this image. The property Richtextbox.xaml does not include any information about the image. It just shows the code like "".
Does anyone have this problem and handle it before?
RichTextBox.Xaml strips out a lot of things, as a security safeguard (more for the setter than the getter as far as I recall, but it does it both ways so there are no round-trip surpises).
I recommend looking at the XAML Serializer written by David Poll on his blog (here: http://www.davidpoll.com/2010/07/25/to-xaml-with-love-an-experiment-with-xaml-serialization-in-silverlight/ ) as it can serialize RTB awesomely well (it's in fact one of the test cases he shows). David was a PM on the Silverlight XAML Parser in SL4, so he knows an awful lot about XAML.
But be careful when setting the .Xaml property, as you could mistakenly end up spinning up InlineUIContainer elements which load resources into your AppDomain that you don't want in there, so make sure you control the inputs or you strip them yourself very carefully.

How unique is XAML?

Was talking to a colleague about XAML and how it is both a presentation and object description language and therefore quite unique and novel among IT technology.
Is this true that XAML is unique and novel?
Does XAML have any counterparts or predecessors in the Java world or elsewhere? I believe someone told me that Java Server Faces was similar to WPF, so what is the equivalent of XAML there?
I know MXML in Flex is similar but as far as I can remember there are some major structural differences, from what I remember MXML doesn't really describe objects but is more of a pure presentation XML.
This is a case of a general technology having such an overwhelming common specific usage that becomes synonmous with the specific usage. For example, discussions of Javascript often assume the browser context and the manipulation of a HTML DOM without anyone having to expressly say so.
Strictly speaking XAML is not like XUL or SVG apart from being XML. XUL, SVG have a defined syntax for declaring User interface or graphical elements, raw XAML does not.
XAML can, for example, also be used to describe Workflows in Workflow foundation.
XAML is actually an approach to reading XML in order to describe types and properties of those types. For example, a property of a type may be described either using an attribute or an Element as long as its name can be interpreted correctly. XAML also includes an extension to the basic XML syntax where { } in an attribute can act as a short hand for a complex element.
I've not come across this sort of thing before. All other XML based technologies come with a specific purpose, XAML is the first usage of XML I've seen that is deviod of any specific nomenclature but just a means of mapping XML to types.
****XAML, XUL, and XHTML Overlap****
The greatest overlap between XAML and other standards lies in its support for concepts drawn from HTML/XHTML. The similarities between XAML and HTML are numerous. Overlap with HTML is not limited to XAML, of course. The other well-known XML GUI dialect—Mozilla's XUL—also overlaps with XHTML. Finally, both XAML and XUL overlap in places that XHTML doesn't even include. XHTML and XUL can be combined in one document (at least in Mozilla browsers). Such a combination is a rough analog for non-Web uses of XAML. In fact, Mozilla's XUL alone is a rough analog for some uses of XAML.
but taken together, they really constitute nothing more than support for most of the basic HTML content and form widgets that are already routine in ordinary Web applications. XUL overlaps XHTML less that XAML does because XUL attempts to separate itself from XHTML. It's not trying to be a drop-in replacement, as XAML is.
One thing I do like about XAML compared with HTML is the increased freedom from the publishing-derived features of HTML. XAML frees you from h1 tags, code tags and a host of other miscellaneous niche tags used infrequently in HTML. For practical purposes, these tags act as little more than style information in modern HTML documents.
HTML is also a poor GUI for applications, despite the popularity of the Web. Both XAML and XUL go a long way towards rectifying that problem. You could re-write your Web applications in XAML and they'd look better than the HTML originals, if only XAML had better CSS support.
Read the comparisons to other presentation technologies with a grain of salt - Xaml is a method of constructing and composing .NET objects. That's in stark contrast to other systems that were designed as a way to build user interfaces. The nice thing about Xaml is that it's independent of the technology stack that its used for - it's a purpose-agnostic declaritive language more like C# than XHTML. In that way, it's unique.
Cocoa from Apple, or event earlier NeXtStep had something similar long before XAML.
The GUI is created with an interface builder, which makes so called nib (Nextstep Interface Builder) files, which contains the layout, bindings, actions, outlets and serialized object instances. In the former time these nib files were stored in a binary file format, but nowadays it is also xml (xib).
So XAML is not the first not unique at all.
Besides XAML, you have XUL which is used by Mozilla. SVG on the other hand, is one recommended by W3C.
Mozilla created their UI description language XUL originally to be able to easily customize the UI of all of their products.
Nowadays it's a package which can be included in other applications and also has an extended functionality.
Although XUL mainly focuses on UI representation it also contains other structures as Events and Scripts and Data sources. Nevertheless as far as I know XAML integrates these concepts much tightlier into their .NET (and attached) frameworks. But I'm not sure if this is enough to call it unique and novel.
XAML is an object graph construction language in the dialect of XML (not the greatest choice). Every XAML element is an object instantiation and the corresponding attributes are property assignments on said instance. Since XML is a string based language, property values need to be converted from their string type into whatever type the property expects. This is done using descendants of TypeConverter that the XAML processor locates and utilizes automatically. XAML and WPF come with a default set of TypeConverters corresponding to their provided types and you can provide your own.
A rough overview of the definition process is as follows:
<classG-in-namespace-A
xmlns="namespace-A"
xmlns:alias-B="namespace-B"
xmlns:alias-C="clr-namespace:namespace-C;assembly=assembly-of-namespace-C"
propertyG1="simple text value stipulation"
propertyG2="{alias-C:classH-in-namespace-C propertyC1=valueC1,..}"
>
<classG-in-namespace-A.propertyG2>
<alias-B:class-I-in-namespace-B propertyB1=valueB1,...>
class-I-in-namespace-B's content property value assignment
</alias-B:class-I-in-namespace-B>
</classG-in-namespace-A.propertyG2>
classG-in-namespace-A's content property value assignment
</classG-in-namespace-A>
There are utility types provided by XAML and WPF beyond TypeConverters that facilitate property assignments. In particular, there are the following:
ResourceDictionary,
ObjectDataProvider,
RelativeSource,
StaticResource,
DynamicResource,
...and more as shown in Microsoft Docs
Well, XAML is basically advanced markup for .NET, therefore I think you can draw a lot of parallels from XAML to XHTML - Both being presentation techniques.
There's a lot of differences as well ofc (XHTML being interpreted by a browser to produce graphics, while XAML is being compiled into MSIL and relying on the CLR to do the graphics :) )

How do I handle/edit large amount of text in WPF?

What would be a good approach to display and edit large amount of unformatted text (just like notepade does) using WPF? Loading a big string into a TextBox makes the UI unresponsive. The overall performance is not nearly comparable with TextBox Controls of previous Microsoft UI Frameworks.
What options do I have to solve this problem. I do not want to block the UI thread while the text control loads the text. Also I might need some sort of "virtualization" because it might not be a good idea to load the whole text into the control (I guess that 20MB of text would create a lot of glyphs even if they are not visible). It seems that TextBox doesn't even have an AppenText() Method anymore so I don't even have a way to control asynchronous loading of the text.
Isn't this a common problem? It seems that WPF does not provide anything for this out of the box. Why is this so?
AvalonEdit, the text editor in SharpDevelop, was written completely from scratch in WPF and is optimized for large amounts of text. It doesn't support rich text (although it does support syntax highlighting and other cool features such as folding). I think this might fit your bill perfectly.
Here is an article on the editor written by the developer:
http://www.codeproject.com/KB/edit/AvalonEdit.aspx
I am not sure if this helps, but have you tried using FlowDocumentPageViewer and FlowDocumentReader?
It also has very good annotations support and looks ideal for loading documents in text format.
The problem is that the TextBox is a single container element. List controls, such as ListBox virtualize very well because of container recycling. There really isn't anything simple that you can do to speed up the TextBox.
But the TextBox control does have an AppendText() method:
TextBox tb = new TextBox();
tb.AppendText("Hello");
So yes, you can use this to dynamicly add some text just like you mentioned.
You can just use a textbox with a style that gives the user more room to view the text. There are probably more advanced controls from Telerik and others but if you don't require editing options that should suffice.
You could always mix and match technologies: you could drop a WinForms TextBox onto a WPF parent. You lose things like styling, opacity, animation, transforms, etc., but if all that matters is editing text, the WinForms TextBox does that just fine.
Have you tried the WPF RichTextBox? You'll definitely want to read up on the FlowDocument information if you go this route.
You could use FlowDocument, but this doesn't work out of the box to bind to the Document property of a FlowDocument in MVVM.
Another solution is using FlowDocumentScrollViewer and bind to its Document property.
(or you could even use a FlowDocumentReader and bind its Document property, similar to the FlowDocumentScrollViewer. This gives you a different UI.)
The View:
<FlowDocumentScrollViewer Document="{Binding FlowDocument, Mode=OneWay}" />
The ViewModel:
FlowDocument fd = new FlowDocument();
Paragraph p = new Paragraph();
Run r = new Run();
r.Text = "large text";
p.Inlines.Add(r);
fd.Blocks.Add(p);
FlowDocument = fd;
private FlowDocument _FlowDocument;
public FlowDocument FlowDocument
{
get{ return _FlowDocument; }
set
{
_FlowDocument = value;
NotifyOfPropertyChange(nameof(FlowDocument));
}
}
see also this for extra performance tips: https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/optimizing-performance-text#flowdocument-textblock-and-label-controls
How about trying something like this:
Keep the whole string in memory but show only a 'slice' of it in the textbox. Size of the that sliced string would be dynamically calculated depending on the size of textbox, font size etc.
Of course this involves a lot of not trivial code for proper displaying, synchronizing and so on, but it seems the way to go.
One other option is to use Scintilla.NET. It has the best performance for large amounts of texts I have seen so far. Loading large files is almost instantaneous. Even though it is a WinForms control, you can embed it into your WPF window with WindowsFormsHost container. There is syntax highlighting and some other features that should be more than enough for displaying unformatted text. From the downsides - since this is a WinForms control, it overlaps other WPF UI elements. Also there may be issues with resizing the control. Unfortunately, I don't see any better option than using a non-WPF control instead of the default TextBox and RichTextBox.

Resources