Note that there are some explanatory texts on larger screens.

plurals
  1. POAmpersand in WPF Binding StringFormat
    text
    copied!<p>I'm trying to create a string format that has a literal string containing an ampersand. I've tried &amp; and &amp; amp; (without the space) but both cause an exception in the VS2010 designer. Here's what I'm working with:</p> <pre><code>Text="{Binding Path=LearningOpportunities, StringFormat='Sharing &amp; Learning Opportunitites:\{0\}'}" </code></pre> <p>If I use '&amp;', it tells me "Entity references or sequences beginning with an ampersand '&amp;' must be terminated with a semicolon ';'". If I use &amp; amp;, it gets a FormatException: "Index (zero based) must be greater than or equal to zero and less than the size of the argument list." I've been doing web development away from WPF for a while so I'm feeling a little rusty. How can I get this working?</p> <p>Edit: There's been a lot of speculation regarding escaping being the culprit and from what I can tell, it's all incorrect. So to get that out of the way here's what works and doesn't work, taking the ampersand out of the equation:</p> <p><strong>Formats that work:</strong></p> <pre><code>StringFormat=Sharing and learning opportunitites:\{0\} StringFormat='Sharing and learning opportunitites:\{0\}' StringFormat={}Sharing and learning opportunitites:{0} StringFormat='{}Sharing and learning opportunitites:{0}' StringFormat=Sharing and learning opportunitites:{0} StringFormat='Sharing and learning opportunitites:{0}' </code></pre> <p><strong>Formats that don't work:</strong></p> <pre><code>StringFormat=Sharing and learning opportunitites:{}{0} StringFormat=Sharing and learning opportunitites:{{0}} (Outputs literal "{0}") </code></pre> <p>So to summarize, you can escape all braces in the string by placing opening and closing braces {} at the <em>beginning</em> of the string, or you can escape individual braces using backslashes. Surprisingly, it still worked without escaping the braces, but the syntax coloring was pretty ugly in Visual Studio. To avoid ugly syntax coloring, you can use single quotes around the format string.</p> <p>So with escaping put to rest, the problem is that adding an ampersand to the format string causes an exception, whether it is escaped or not. The only difference between escaped and not escaped is it gives a different exception.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload