1

I have a listBox of color and I want to get the selected color String for example: Red,yellow.

The problem is when I get the selectedItem I need to cast it to System.Windows.Media.Color to get the name and put it into string to use it in other case. Here is the code I used ,Unfortunately I always get this exception

Specified cast is not valid.

System.Windows.Media.Color colo = (System.Windows.Media.Color)listColor.SelectedItem;

Any help would be so appreciated

MRebai
  • 5,344
  • 3
  • 33
  • 52

5 Answers5

3

In XAML a string is so easily converted to a color that you hardly realize they are very different types. In C# you will have to convert it explicitly. Luckily there is a built-in class that can do that:

string colorName = (string) listColor.SelectedItem;
Color colorValue = ColorConverter.ConvertFromString(colorName);
H H
  • 263,252
  • 30
  • 330
  • 514
1

Use the SelectedValue instead:

System.Windows.Media.Color color = (System.Windows.Media.Color)listColor.SelectedValue;
Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70
1

fixed it with

Blockquote Color colorValue = (Color)((System.Reflection.PropertyInfo)listColor.SelectedValue).GetValue(listColor, null) ;

MRebai
  • 5,344
  • 3
  • 33
  • 52
  • This is the only fix that works - It's a ridiculous leap to get from Color to Color (in the same namespace) – T4NK3R Sep 12 '16 at 17:27
0

When you add items to your listbox, you actually add Objects. Which means that what you see as a text in each of your list item, is the object you added .ToString().

So if you're adding string, you'll get back string. If you're adding Color, you'll get back Color.

In your case, you seem to add string. Of course you can't cast a string directly in a color, so either you should add the object Color to your list, or you should parse the string you get with SelectedValue to get a Color.

If you want to add directly the object Color, you can also use the property SelectedValuePath to set the property of your object that will be displayed in the list.

Also you should take a look at this post to see the difference between SelectedValue and SelectedItem: Difference between SelectedItem, SelectedValue and SelectedValuePath

Community
  • 1
  • 1
ppetrov
  • 3,077
  • 2
  • 15
  • 27
0

Try this->

          Color ChosenColor;
          string SelectedColor= (string)listColor.SelectedItem;;

          ChosenColor=(Color)ColorConverter.ConvertFromString(SelectedColor);
Vishal
  • 604
  • 1
  • 12
  • 25