0

Is it possible to set the FontWeight of a ComboBoxItem like so?

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

Visual Studio likes this code, but at runtime i get a NullReferenceException.

Alternatively I could use this code, but I am looking for something smarter:

  ComboBoxItem temp = new ComboBoxItem();
  temp.FontWeight = FontWeights.Bold;
  temp.Content = "foo";
  comboCategory.Items.Add(temp);
Johann
  • 523
  • 9
  • 22
  • Well, I only have 4-5 ComboBoxItems where the FontWeight should be bold. So I don't really need to set my own DrawMode. Maybe somebody can explain, why my first code example throws that Exception. – Johann Mar 14 '13 at 11:04

1 Answers1

1

ComboBox's Items.Add() function accepts a type of object which in your first example is a string and then the line below you are trying to cast a string to a ComboBoxItem, hence your null reference exception.

If you want access to the font weight properties then you have to do something similar to your second suggestion in regards to creating your ComboBoxItem first and passing that into the Add() function.

You could potentially "simplify" your code like the following, but this is a matter of opinion whether this code is cleaner:

comboCategory.Items.Add(new ComboxBoxItem() {FontWeight = FontWeights.Bold, Content = "foo"});
Oliver
  • 8,794
  • 2
  • 40
  • 60
robasaurus
  • 1,022
  • 8
  • 15