Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting selected item string from bound ListBox

I'm having a problem with getting a string from a bound textblock within a listbox, when I use the code below, I can bind the listbox and the listbox has items showing up, but when the item in the list is clicked I don't get the proper string, I print a message box a message with objects names like

"MyApp.Item"

shows up instead. myApp is the name of the app and Item is the name of my model that I am binding to the listbox. The proper text from the selected item showed up when the listbox was not binded.

private void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
    selectedText = "";

    selectedText = listBox.SelectedValue.ToString();

    MessageBox.Show(selectedText);
}

xml

<ListBox ItemsSource="{Binding Item}" Foreground="RoyalBlue" 
    Height="395" HorizontalAlignment="Center" 
    Margin="12,111,0,0" Name="listBox" 
    VerticalAlignment="Top" Width="438"
    TabIndex="10"  Tap="listBox_Tap" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock TextWrapping="Wrap" FontSize="26" HorizontalAlignment="Left"
                Name="tblItem" Text="{Binding ItemString}"
                VerticalAlignment="Top" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

I'd really appreciate if you could help me thanks

like image 639
M_K Avatar asked May 14 '26 19:05

M_K


1 Answers

You're binding to the ItemString in the DataTemplate's TextBlock and the Item Collection in the ListView. As such the SelectedValue will be of the Item type. You should actually be doing something like this in your Tap handler to get at the ItemString's value...

private void listBoxtrend_Tap(object sender, GestureEventArgs e)
{
    selectedText = "";

    var selected = listBox.SelectedValue as Item;
    selectedText = selected.ItemString;

    MessageBox.Show(selectedText);
}

In your example, the ToString is printing the name of the class. You could also override ToString in your Item model to be whatever you want the string to be.

Note: the types and such may be a bit off, I guessed a bit based off of what you wrote in your question. Also, there is no need to set selectedText to an empty string that will just be overwritten in the third line above. I wanted to keep it so you could get some idea of what I changed in your code.

like image 172
scottheckel Avatar answered May 16 '26 10:05

scottheckel