Highlighting SelectedItem from WPF Combobox to Color throws an exception

I have combobox data binding to available system colors. When the user selects a color, the following code is run:

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

This throws a cast exception with the following message: "The specified cast is invalid." When I hover over cboFontColour.SelectedItem in the debugger, it is always a Color object.

I do not understand why the system, it would seem, cannot distinguish it from Color to Color, any help will be very necessary.

+3
source share
4 answers

. , , DependancyProperty . ,

0

is as . , , , .

0

? SystemColors, , , , Color ( SolidColorBrushes ResourceKeys).

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

.

0

I had the same problem and none of the suggestions on this issue worked. I kept getting exceptions when I tried to use (Color), and the code didn’t even compile if I tried to use “Color”? or how". Exited the next workaround. This is not ideal, because now I need to create a new object, but at least it works:

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

Source: https://habr.com/ru/post/1741260/


All Articles