Laurent Resman
Laurent Resman

Reputation: 133

How to get data to string/int from ListBox ( ListBoxItems) Windows Universal

I hope no one already asked question like this before, I did a little research but non of answers worked for me, so I decided to ask it myself. I'm making an simple app where user have to chose few options from the list, I already made ListBox and list of items.

<ListBox x:Name="Continent">
            <ListBoxItem Content="Europe" Foreground="White" />
            <ListBoxItem Content="Africa" Foreground="White"/>
            <ListBoxItem Content="Asia" Foreground="White"/>
</ ListBox>

I'm quite new to Windows Universal Platform so I hope I done it right.

Anyway, now I would like, after user press "forward" button collect that data to an STRING for example. I tried with:

string selected = Continent.SelectedItem.Content;

and

string selected = Continent.SelectedItems[0].Content;

I also tried to add "text" value but it doesn't let.

Does anyone know how to do that? What's the most simple way?

Thanks in advance

Upvotes: 0

Views: 130

Answers (2)

Micha&#235;l Fery
Micha&#235;l Fery

Reputation: 66

it's not a good idea to use the content of your listboxitem. These controls have specific property to contain logic data and it's called 'tag'. You can put everything you want in it like complex objects and have a different display (content) value.

So you have to change your xaml to this :

<ListBox x:Name="Continent">
    <ListBoxItem Content="Europe" Foreground="White" Tag="europe" />
    <ListBoxItem Content="Africa" Foreground="White" Tag="africa"/>
    <ListBoxItem Content="Asia" Foreground="White" Tag="asia"/>
</ListBox>

and your code-behind to this :

foreach (ListBoxItem selectedItem in Continent.SelectedItems)
{
  var continentTag = selectedItem?.Tag as string;
  if (continentTag != null)
  {
    //Do your stuff here
  }
}

Upvotes: 0

Kory Gill
Kory Gill

Reputation: 7163

I think a reasonable answer here is to help you learn how to debug problems on your own, and discover things as you progress learning the platform.

The example you have is pretty simple. Most of the time, the Content would be set to an instance of a class, like a Continent object. However, what you have is fine, you just have to use the debugger to learn about the objects you are getting back.

For this: var data = Continent.SelectedItem;, you can see the following in the Immediate window:

data is ListBoxItem
true
(data as ListBoxItem).Content
"Africa"
(data as ListBoxItem).Content is string
true
((ListBoxItem)data).Content
"Africa"

Play around in the debugger when you get stuck, use the Immediate window, or look at Locals to discover the types being returned.

So your answer might be:

string selected = ((ListBoxItem)data).Content

Good luck with your project.

Upvotes: 1

Related Questions