【问题标题】:How to set value of ListBox as a string如何将 ListBox 的值设置为字符串
【发布时间】:2021-04-02 13:36:31
【问题描述】:

我在 for 循环中有以下代码:

ComboboxItem itemb = new ComboboxItem();
itemb.Text = item.gameName;
itemb.Value = item.name;

ASCII_FriendList.Items.Add(itemb);

ASCII_FriendList 是 ListBox,我想显示 item.gameName 因为 item.name 是一个随机的 uuid,因此不可读。游戏名称很容易识别。

到目前为止我还没有找到解决方案,我有什么替代方案?

【问题讨论】:

  • Add(item.gameName) ?
  • 我需要使用“name”作为值,gameName只是将uuid关联到值的一种方式
  • 但是我不能存储“name”,因为它是一个字符串
  • 是 WinForms 吗? WPF?对于 WPF,您应该在 xaml 中使用 ItemTemplate。
  • 这是winforms! (从未使用过 wpf)

标签: c# winforms listbox


【解决方案1】:

IIRC 您可以执行以下操作:

ASCII_FriendList.Items.Add(item);

其中item任何 对象(例如您的对象包含namegameName),我将其类型称为T

然后像这样钩住Format事件:

public Main()
{
    InitializeComponent();
    ASCII_FriendList.Format += ASCII_FriendList_Format; //You can press tab at += in VS to auto-create the method body.
}


private void ASCII_FriendList_Format(object sender, ListControlConvertEventArgs e)
{
    //e.Value will be the string that will display in the list on the form.
    if(!(e.ListItem is T))
        e.Value = "ListItem isn't T"; //e.ListItem wasn't T, so we can't access gameName
    else
        e.Value = ((T)e.ListItem).gameName; //Cast e.ListItem to T, then access its gameName property
}

这将使ASCII_FriendList.SelectedItem 成为T 类型的对象(假设您通过执行(T)ASCII_FriendList.SelectedItem 对其进行转换),同时在表单中可见地显示T.gameName

【讨论】:

    猜你喜欢
    • 2022-01-06
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多