C# 列表框所选项目内容到文本块

C# 列表框所选项目内容到文本块,c#,windows-phone-7,listbox,C#,Windows Phone 7,Listbox,我相信有一个简单的解决办法,但我现在似乎找不到 我正在尝试使用下面的代码将textblock中的selection listbox的内容禁用为文本 private void SelectionToText(object sender, EventArgs e) { ListBoxItem selection = (ListBoxItem)TextListBox.SelectedItem; selectionText.Text = "This is the " + selecti

我相信有一个简单的解决办法,但我现在似乎找不到

我正在尝试使用下面的代码将textblock中的selection listbox的内容禁用为文本

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

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

}
出于某种原因,文本块只是显示出来

“这是System.Windows.Controls.ListBoxItem”

我最初认为这是因为我还没有转换成字符串,但这也不起作用


有什么建议吗?

您可以引用ListBoxItem的Content属性

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

您可以创建自定义类

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;
    }
}
将项目添加到
列表框中,如:

listBox1.Items.Add(new MyListBoxItem("1", "Text"));
这就行了

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

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

}

如果我没有错,您需要执行以下代码

Convert.ToString(TextListBox.SelectedItem);
这将返回SelectedItem的值,请这样写:

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

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

}

或者,在silverlight中,通过将textblock的text属性绑定到listbox的selecteditem.content属性,您可以在不使用代码隐藏的情况下完成此操作

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


其中list是我的ListBox的名称。

首先不要强制转换到ListBoxItem。您的ListBox内容的类型是什么?@EugeneCheverda ListBox的内容是字符串,例如。。谢谢你,我真不敢相信我错过了。我想我需要睡一会儿。效果很好。干杯
<TextBlock Text="{Binding SelectedItem.Content, ElementName=list}"/>