Rhys
Rhys

Reputation: 2877

LIstbox Selected Item content to textblock

I am sure there is a simple solution to this, but I can't seem to find it at the moment.

I am trying to disaply the content of the selection listbox in a textblock as text using the below code.

private void SelectionToText(object sender, EventArgs e)
{
    ListBoxItem selection = (ListBoxItem)TextListBox.SelectedItem;

    selectionText.Text = "This is the " + selection;

}

For some reason the textblock just displays

"This is the System.Windows.Controls.ListBoxItem "

I initial thought it was because I hasn't converted to a string, but that didn't work either.

Any suggestions?

Upvotes: 2

Views: 5378

Answers (6)

Rich Hopkins
Rich Hopkins

Reputation: 1891

Or you can do it without code behind, in silverlight, by binding the text property of the textblock to the selecteditem.content property of the listbox.

<TextBlock Text="{Binding SelectedItem.Content, ElementName=list}"/>

Where list is the name of my ListBox.

Upvotes: 0

Razvan Trifan
Razvan Trifan

Reputation: 544

string selText = selection.Items[selection.SelectedIndex].Text;

Upvotes: 1

Parth Patel
Parth Patel

Reputation: 258

Please write as this:

private void SelectionToText(object sender, EventArgs e)
{
    MyListBoxItem selection = (MyListBoxItem)TextListBox.SelectedItem;

    selectionText.Text = "This is the " + selection.Content.ToString();

}

Upvotes: 0

wdavo
wdavo

Reputation: 5110

You can reference the Content property of the ListBoxItem

selectionText.Text= "This is the " + selection.Content.ToString();

Upvotes: 3

abc
abc

Reputation: 83

If I am not wrong, you need to do the following code

Convert.ToString(TextListBox.SelectedItem);

This will return the value of SelectedItem

Upvotes: 0

Abdul Munim
Abdul Munim

Reputation: 19217

You can create a custom class

public class MyListBoxItem
{
    public MyListBoxItem(string value, string text)
    {
        Value = value;
        Text = text;
    }

    public string Value { get; set; }
    public string Text { get; set; }

    public override string ToString()
    {
        return Text;
    }
}

Add items to your ListBox like:

listBox1.Items.Add(new MyListBoxItem("1", "Text"));

And this will work

private void SelectionToText(object sender, EventArgs e)
{
    MyListBoxItem selection = (MyListBoxItem)TextListBox.SelectedItem;

    selectionText.Text = "This is the " + selection;

}

Upvotes: 0

Related Questions