MRebai
MRebai

Reputation: 5474

How to cast a selecteditem in listbox

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

Upvotes: 1

Views: 4030

Answers (5)

MRebai
MRebai

Reputation: 5474

fixed it with

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

Upvotes: 1

Vishal
Vishal

Reputation: 624

Try this->

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

          ChosenColor=(Color)ColorConverter.ConvertFromString(SelectedColor);

Upvotes: 0

ppetrov
ppetrov

Reputation: 3105

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

Upvotes: 0

Henk Holterman
Henk Holterman

Reputation: 273244

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);

Upvotes: 3

Fabian Bigler
Fabian Bigler

Reputation: 10895

Use the SelectedValue instead:

System.Windows.Media.Color color = (System.Windows.Media.Color)listColor.SelectedValue;

Upvotes: 1

Related Questions