LIstbox Selected Item content to textblock

2020-02-13 03:56发布

问题:

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?

回答1:

You can reference the Content property of the ListBoxItem

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


回答2:

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


回答3:

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;

}


回答4:

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

Convert.ToString(TextListBox.SelectedItem);

This will return the value of SelectedItem



回答5:

Please write as this:

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

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

}


回答6:

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.