WPF string escaping - Exception is thrown while creating control template
I am trying to construct a Control template from code behind. Things were working fine till recently I found that the code was throwing an exception because of escape characters in string. The error message is dynamically constructed by retrieving from resource file.
The exception is
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll Additional information: Name cannot begin with the '@' character, hexadecimal value 0x40. Line 1, position 537.
//In this case when exception is thrown,
//string errorMessage = "Name cannot contain any of the following characters $ \" @ ; ^ | "
public static ControlTemplate GetErrorTemplate(string errorMessage)
{
string xamlString = "<ControlTemplate xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" " +
"xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" " +
"xmlns:nicefx=\"clr-namespace:NiceFx.Interop.UIComponents;assembly=NiceFx\" " +
"xmlns:wpfkit=\"http://schemas.microsoft.com/wpf/2008/toolkit\" >" +
开发者_JAVA百科 " <DockPanel LastChildFill=\"True\">" +
"<TextBlock Foreground=\"White\" Background=\"Red\" FontSize=\"12\" Padding=\"2\" FontFamily=\"Trebuchet MS\" Margin=\"5,5,0,0\" TextWrapping=\"Wrap\" DockPanel.Dock=\"Bottom\" Text=\"" + errorMessage + "\"></TextBlock>" +
"<AdornedElementPlaceholder />" +
" </DockPanel>" +
" </ControlTemplate>";
//EXCEPTION OCCURS IN THIS LINE
ControlTemplate ct = (ControlTemplate)XamlReader.Load(XmlReader.Create(
new StringReader(xamlString)));
return ct;
}
How do I escape this string? I tried all possible ways but I am unable to do so.
According to the comment in your code, errorMessage contains a "
, which will be inserted (without escaping it) into the XAML you are constructing. This "
will then act as the closing quote of the Text
attribute. At this point, the next non-whitespace character the parser encounters will be @
, which is not an allowed character for the name of a XAML attribute, so it stops and reports the error.
That covers the why. As for how to escape it, you can use the XML entity for double quote: "
Note that you may need to apply this escaping to multiple characters in your parameter.
精彩评论