0

是否可以像这样设置 ComboBoxItem 的 FontWeight ?

  comboCategory.Items.Add("foo");
  (comboCategory.Items[0] as ComboBoxItem).FontWeight = FontWeights.Bold;

Visual Studio 喜欢这段代码,但在运行时我得到一个 NullReferenceException。

或者我可以使用这段代码,但我正在寻找更聪明的东西:

  ComboBoxItem temp = new ComboBoxItem();
  temp.FontWeight = FontWeights.Bold;
  temp.Content = "foo";
  comboCategory.Items.Add(temp);
4

1 回答 1

1

ComboBox 的Items.Add()函数接受object在您的第一个示例中为 a的类型string,然后您尝试将下面的行强制转换string为 a ComboBoxItem,因此您的空引用异常。

如果您想访问字体粗细属性,那么您必须执行与您的第二个建议类似的操作,以创建您的ComboBoxItem第一个并将其传递给Add()函数。

您可能会像下面这样“简化”您的代码,但对于此代码是否更清洁,这是一个见仁见智的问题:

comboCategory.Items.Add(new ComboxBoxItem() {FontWeight = FontWeights.Bold, Content = "foo"});
于 2013-03-14T11:08:59.517 回答