首页 > 解决方案 > 如何拉出listview选中条目的item和subitem

问题描述

我想编辑一个由 2 个整数和 3 个字符串组成的列表视图项。我正在将项目从公共类“Rineitem”保存到列表视图中。我可以将选定的行分配给一个对象并在我的本地窗口中查看它,但我不知道如何访问它或它的子项。

我试图找到示例,但没有发现任何应该如此简单的东西。我自己的尝试经常给出信息,也许我忘记了演员表!???如果我将对象转换为字符串,我会得到一个命名公共类的文本。

object item = lvw_Smd_Jobs.SelectedItem;

当我尝试将 lvw selectedItem 分配给我得到的类时,无法将类型“object”隐式转换为“Rin...Auftrag_Verwalter.Rineitem”。存在显式转换(您是否缺少演员表?)我想将两个字符串值保存到用户可以更改值的文本框中,然后我将保存列表视图项及其更改。

标签: c#wpflistview

解决方案


您可以将“ListBoxItem”(类型对象)投射到它真正的类。

这里有一个小例子,如何在您的 : 中添加、读取和修改项目ListBox

// Example class
public class RineItem
{
    public string Name { get; set; }
    public int Id { get; set; }

    // Override ToString() for correct displaying in listbox
    public override string ToString()
    {
        return "Name: " + this.Name;
    }
}

public MainWindow()
{
    InitializeComponent();

    // Adding some examples to our empty box
    this.ListBox1.Items.Add(new RineItem() { Name = "a", Id = 1 });
    this.ListBox1.Items.Add(new RineItem() { Name = "b", Id = 2 });
    this.ListBox1.Items.Add(new RineItem() { Name = "c", Id = 3 });
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    // Loop through SelectedItems
    foreach (var item in this.ListBox1.SelectedItems)
    {
        // Have a look at it's type. It is our class!
        Console.WriteLine("Type: " + item.GetType()); 
        // We cast to the desired type
        RineItem ri = item as RineItem;
        // And we got our instance in our type and are able to work with it.
        Console.WriteLine("RineItem: " + ri.Name + ", " + ri.Id); 

        // Let's modify it a little
        ri.Name += ri.Name;
        // Don't forget to Refresh the items, to see the new values on screen
        this.ListBox1.Items.Refresh();
    }
}

您面临的错误消息告诉您,没有隐式转换来转换object为和 RineItem。

有可能的隐式转换(从 int 到 long)。你可以创造你自己的。这里有一个例子:

public class RineItem2
{
    public string Name2 { get; set; }
    public int Id2 { get; set; }

    public static implicit operator RineItem(RineItem2 o)
    {
        return new RineItem() { Id = o.Id2, Name = o.Name2 };
    }
}

现在你可以这样做:

RineItem2 r2 = new RineItem2();
RineItem r = r2;

但是只有在 Class 中的每个对象RineItem2都可以转换为RineItem.

object到到的演员RineItem每次都必须工作!因此,您不知道您不允许使用的对象是什么类型:

object o = "bla bla";
RineItem r = (RineItem)o; // Not allowed! Will not work!

推荐阅读