views:

236

answers:

4

I have a combobox databound to the available system colors. When the user selects a color the following code is fired:

private void cboFontColour_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    Color colour = (Color)(cboFontColour.SelectedItem);
}

This throws a Casting Exception with the following message: "Specified cast is not valid." When I hover over cboFontColour.SelectedItem in the debugger, it is always a Color object.

I do not understand why the system seemingly cannot cast from Color to Color, any help would be much obliged.

+1  A: 

You should always use is and as instead of direct type conversion. Additionally make sure that Color is actually the same type you see in the Debugger.

Danvil
I tried that, but I get a compile error:Error 8 The as operator must be used with a reference type or nullable type ('System.Windows.Media.Color' is a non-nullable value type)
Nick Udell
@Nick Udell, you can do `Color? colour = cboFontColour.SelectedItem as Color?;`, and then check if it's null. Read more on `is` and `as` and so on on other, complete, threads about it.
ANeves
That works brilliantly, thanks
Nick Udell
Just curious: then how do you get the Color value if the value is not a Color?!
gehho
Color? color =.... and then color.Value
LnDCobra
+1  A: 

Try using the SelectedValue property instead. As far as I am concerned, SelectedItem returns the ComboBoxItem which wraps the Color, while SelectedValue returns the actual Color value.

gehho
That gives me exactly the same error
Nick Udell
I believe not, You can bind the ComboBox value to a certain value of an item. SelectedItem will return the item selected from the itemssource.
LnDCobra
A: 

How did you set up the binding to the available system colors? If you are using the static properties of the SystemColors class then note that despite the name of the class, not all of these entries are Color objects (but SolidColorBrushes and ResourceKeys too). You can always do an

    MessageBox.Show(cboFontColour.SelectedItem.GetType().ToString());
    // or
    MessageBox.Show(cboFontColour.SelectedValue.GetType().ToString());

to check the type.

kicsit
A: 

Ahh finally solved it. What the function actually returned was a DependancyProperty instead of a Color. Not sure how I missed it for so long

Nick Udell