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?
You can reference the Content property of the ListBoxItem
selectionText.Text= "This is the " + selection.Content.ToString();
string selText = selection.Items[selection.SelectedIndex].Text;
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;
}
If I am not wrong, you need to do the following code
Convert.ToString(TextListBox.SelectedItem);
This will return the value of SelectedItem
Please write as this:
private void SelectionToText(object sender, EventArgs e)
{
MyListBoxItem selection = (MyListBoxItem)TextListBox.SelectedItem;
selectionText.Text = "This is the " + selection.Content.ToString();
}
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.