开发者

Casting SelectedItem of WPF Combobox to Color causes exception

开发者 https://www.devze.com 2022-12-27 12:57 出处:网络
I have a combobox databound to the available system colors. When the user selects a color the following code is fired:

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 syste开发者_开发技巧m seemingly cannot cast from Color to Color, any help would be much obliged.


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.


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.


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


I was getting the same problem, and none of the suggestions from this question worked. I kept getting exceptions when trying to cast as (Color), and the code wouldn't even compile if I tried using 'Color?' or 'as'. Ended up coming up with the following workaround. It's not ideal, because I now have to create a new object, but at least it works:

string colorName = _comboBox.SelectedValue.ToString();
Color color = (Color)ColorConverter.ConvertFromString(colorName);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号