如何在 ComboBoxItem 的内容中包含与号(&)

我现在有一个 Combobox,如下所示:

//XAML
<ComboBox>
<ComboBoxItem> Awake & Alive</ComboBoxItem>
</ComboBox>

这引发了一个错误: 实体引用或以“ &”开头的序列必须以分号“ ;”结束。

我假设我错过了某种转义序列,以允许我使用 a & 。如何将这个 comboboxitem 的内容设置为包含 a & ?

41928 次浏览

Use &amp; to encode the ampersand.

//XAML
<ComboBox>
<ComboBoxItem> Awake &amp; Alive</ComboBoxItem>
</ComboBox>

The short answer is to use &amp; to encode an ampersand.

See also Entities: Handling Special Content on XML.com:

At the lowest levels an XML parser is just a program that reads through an XML document a character at a time and analyzes it in one way or another, then behaves accordingly. It knows that it's got to process some content differently than other content. What distinguishes these special cases is the presence of such characters as "&" and "<". They act as flags to the parser; they delimit the document's actual content, alerting the parser to the fact that it must do something at this point other than simply pass the adjacent content to some downstream application.

... So one way to get around your immediate problem is to replace the ampersand in your content with the appropriate entity reference: <company>Harris &amp; George</company>.

Alternatively, you can use the CDATA tag around the contents of the ComboBoxItem element; I think it better maintains the text's readability.

//XAML
<ComboBox>
<ComboBoxItem><![CDATA[Awake & Alive]]></ComboBoxItem>
</ComboBox>

For reference: http://www.w3schools.com/xmL/xml_cdata.asp