Print Page | Close Window

TIP: XAML Markup & Entities (Dynamic)

Printed From: Codejock Forums
Category: General
Forum Name: XAML Snippets
Forum Description: Post your XAML snippets here for everyone to enjoy :)
Printed Date: 22 May 2019 at 7:07pm

Topic: TIP: XAML Markup & Entities (Dynamic)
Posted By: jpbro
Subject: TIP: XAML Markup & Entities (Dynamic)
Date Posted: 01 June 2008 at 10:43pm

Sometimes you need to insert dynamically generated text from XAML unaware sources (such as user input, log files, etc...). Trying to include this text may cause the markup to be invalid and prevent the CJ controls from displaying the markup properly.

To prevent this, you should sanitize all plain-text that you want to add to your markup controls before sending it to the control. Right now I'm using this function and it has been working (although I don't know if the list is exhaustive, so I'd appreciate any input if there are bugs):

Public Function xamlEncodePlaintext(ByVal pPlainText As String) As String
   ' Convert illegal characters to XAML entities
   pPlainText = Replace$(pPlainText, "&", "&")
   pPlainText = Replace$(pPlainText, "<", "&lt;")
   pPlainText = Replace$(pPlainText, ">", "&gt;")
   pPlainText = Replace$(pPlainText, "'", "&apos;")
   pPlainText = Replace$(pPlainText, """", "&quot;")
   ' Expand VB newline characters to XAML <LineBreak/> tags
   pPlainText = Replace$(pPlainText, vbNewLine, "<LineBreak/>")
   xamlEncodePlaintext = pPlainText
End Function

I've also added (as a convenience) the conversion of VB NewLines to <LineBreak/> elements to preserve line spacing.

To use it (for this example, put a TextBox (Text1) and a CJ Label (Label1) on your form):

Private Sub Form_Load

Me.Text1.Text = "<This is a test of plain-text XAML entity encoding & markup>" & vbNewline & vbNewline & "You shouldn't see any XAML in your label caption!"
With Me.Label1   ' CJ label
    .EnableMarkup = True
    .Caption = "<TextBlock>" & xamlEncodePlaintext(Me.Text1.Text) & "</TextBlock>"
End With

End Sub

Pretty simple & straight-forward, but hopefully it will be of some use to someone!

Product: Xtreme SuitePro (ActiveX) version 16.2.6
Platform: Windows XP - SP3

Language: Visual Basic 6.0 SP6

Posted By: zitz
Date Posted: 02 November 2009 at 10:00am
Thank you! I use '&#x0a;' instead '<linebreak/>'

For C++, MFC

CString CMarkupHelper::StringToMarkupFormat( LPCTSTR szString )
    CString sString = szString;
    sString.Replace( _T("&"), _T("&amp;") );
    sString.Replace( _T("<"), _T("&lt;") );
    sString.Replace( _T(">"), _T("&gt;") );
    sString.Replace( _T("'"), _T("&apos;") );
    sString.Replace( _T("\""), _T("&quot;") );
    sString.Replace( _T("\r\n"), _T("&#x0a;") );
    sString.Replace( _T("\n"), _T("&#x0a;") );
    return sString;

Xtreme ToolkitPro v13.1.0, static, VC++6

Print Page | Close Window