【问题标题】:LIstbox Selected Item content to textblock列表框选定项目内容到文本块
【发布时间】:2011-10-26 00:04:42
【问题描述】:

我确信有一个简单的解决方案,但我目前似乎找不到它。

我正在尝试使用以下代码将文本块中选择列表框的内容显示为文本。

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

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

}

由于某种原因,文本块只是显示

"这是 System.Windows.Controls.ListBoxItem"

我最初以为是因为我没有转换成字符串,但那也没有用。

有什么建议吗?

【问题讨论】:

  • 一开始不要转换为 ListBoxItem。你的 ListBox 内容是什么类型的?
  • @EugeneCheverda 列表框内容为字符串,例如.. "item1"

标签: c# windows-phone-7 listbox


【解决方案1】:

可以引用 ListBoxItem 的 Content 属性

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

【讨论】:

  • 谢谢你,我不敢相信我错过了。我想我需要睡觉了。那工作得很好。干杯。
【解决方案2】:
string selText = selection.Items[selection.SelectedIndex].Text;

【讨论】:

    【解决方案3】:

    您可以创建自定义类

    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;
        }
    }
    

    将项目添加到您的ListBox,例如:

    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;
    
    }
    

    【讨论】:

      【解决方案4】:

      如果我没记错的话,你需要做如下代码

      Convert.ToString(TextListBox.SelectedItem);
      

      这将返回 SelectedItem 的值

      【讨论】:

        【解决方案5】:

        请这样写:

        private void SelectionToText(object sender, EventArgs e)
        {
            MyListBoxItem selection = (MyListBoxItem)TextListBox.SelectedItem;
        
            selectionText.Text = "This is the " + selection.Content.ToString();
        
        }
        

        【讨论】:

          【解决方案6】:

          或者您可以在silverlight 中通过将文本块的文本属性绑定到列表框的selecteditem.content 属性来实现,而无需代码。

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

          其中 list 是我的 ListBox 的名称。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2011-10-27
            • 1970-01-01
            • 2018-01-06
            • 1970-01-01
            • 2012-05-08
            相关资源
            最近更新 更多