C# 如何将ListBox的值设置为字符串

C# 如何将ListBox的值设置为字符串,c#,winforms,listbox,C#,Winforms,Listbox,我在for循环中有以下代码: ComboboxItem itemb = new ComboboxItem(); itemb.Text = item.gameName; itemb.Value = item.name; ASCII_FriendList.Items.Add(itemb); ASCII_FriendList是列表框,我想显示item.gameName,因为item.name是随机uuid,因此不可读。游戏名称很容易识别 到目前为止,我还没有找到解决方案,我有什么选择?IIRC您可

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

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

ASCII_FriendList.Items.Add(itemb);
ASCII_FriendList是列表框,我想显示item.gameName,因为item.name是随机uuid,因此不可读。游戏名称很容易识别


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

IIRC您可以执行以下操作:

ASCII_FriendList.Items.Additem

其中item是任何对象,例如包含name和gameName的对象,我将其类型称为T

然后钩住格式化事件,如下所示:

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\u FriendList.SelectedItem成为类型为T的对象,假设您通过执行TASCII\u FriendList.SelectedItem进行强制转换,同时在表单中可见地显示T.gameName。

IIRC您可以执行以下操作:

ASCII_FriendList.Items.Additem

其中item是任何对象,例如包含name和gameName的对象,我将其类型称为T

然后钩住格式化事件,如下所示:

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\u FriendList.SelectedItem成为类型为T的对象,假设您通过执行TASCII\u FriendList.SelectedItem对其进行强制转换,同时在表单中显示T.gameName。

Additem.gameName?我需要使用name作为值,gameName只是一种将uuid与值关联的方法,但我无法存储名称,因为它是字符串,是WinForms吗?WPF?对于WPF,您应该在xaml中使用ItemTemplate。它是winforms!从未使用过wpfadItem.gameName?我需要使用名称作为值,gameName只是将uuid与值关联的一种方式,但我无法存储名称,因为它是字符串,是WinForms吗?WPF?对于WPF,您应该在xaml中使用ItemTemplate。它是winforms!从未使用过wpf