无法从listview WPF中的选定项获取值

时间:2010-11-09 20:49:53

标签: c# wpf xaml listview

我有一个表单,用户可以输入有关新库存项目(ID,标题,价格,日期等)的数据。输入的数据将保存到集合中,然后在列表视图中重新显示。

我得到一个“指定的强制转换无效”,指向“key =(int)lvwInventory.SelectedItems [0];”在尝试提取所选值时。我正在尝试获取ID并使用它打开该项目的编辑窗口。

我在这里做错了什么?

列出有问题的视图

<ListView Height="249" HorizontalAlignment="Left" Margin="27,28,0,0" Name="lvwInventory" VerticalAlignment="Top" Width="384" ItemsSource="{Binding col}">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Type" DisplayMemberBinding="{Binding Type}" />
            <GridViewColumn Header="Title" DisplayMemberBinding="{Binding Title}" />
            <GridViewColumn Header="Price" DisplayMemberBinding="{Binding Price}" />
            <GridViewColumn Header="Date Added" DisplayMemberBinding="{Binding Date}" />
        </GridView>
    </ListView.View>
</ListView>

stockobject class

public class StockObject
    {
        // create stock object properties
        public int ID { get; set; }
        public string Title { get; set; }
        public DateTime Date { get; set; }
        public double Price { get; set; }
        public char Type { get; set; }

试图从所选项目中获取价值的事件

private void btnViewItem_Click(object sender, RoutedEventArgs e)
    {
        int key;

        if (lvwInventory.SelectedIndex == -1) return;

        key = (int)lvwInventory.SelectedItems[0];

        StockObject s = col[key];
        bookDialog.View(s);
    }

3 个答案:

答案 0 :(得分:6)

所选项目是StockObject本身,这就是为什么它不允许你将它转换为int。你需要这样的东西:

var selectedStockObject = lvwInventory.SelectedItems[0] as StockObject;
if(selectedStockObject == null)
{
   return;
}

key = selectedStockObject.ID; //I'm assuming you want the ID as your key

答案 1 :(得分:2)

问题是你的列表视图是绑定col的,StockObject恰好是SelectedItems[0]的集合。因此,StockObjectint,而不是key = (int)lvwInventory.SelectedItems[0]; StockObject s = col[key];

而不是

StockObject s = (StockObject)lvwInventory.SelectedItems[0];

你只需要

private void btnViewItem_Click(object sender, RoutedEventArgs e)
{
    StockObject s = lvwInventory.SelectedItem;
    if (s != null)
        bookDialog.View(s);
}

也许你想要SelectedItem

{{1}}

答案 2 :(得分:1)

这是我得到它的方式!

获取Listview项目

SearchedPurchases Purchase_Invoice = (SearchedPurchases)listView1.SelectedItems[0];
string PurchaseInvoice = Purchase_Invoice.InvoiceNo;