如何从多个选定的列表视图中获取选定的值

如何从多个选定的列表视图中获取选定的值

本文介绍了如何从多个选定的列表视图中获取选定的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我在xaml中有多个选择的listview:

Hello, I have listview with multiple selection in xaml:

<ListView  Name="dgDane" SelectionMode="Multiple" ItemsSource="{Binding Dane}" HorizontalAlignment="Left" Margin="22,79,0,0" VerticalAlignment="Top" Height="310" Width="645">
<ListView.View>
    <GridView>
        <GridViewColumn  DisplayMemberBinding="{Binding Path = ID}" Width="30"/>
        <GridViewColumn  DisplayMemberBinding="{Binding Path = Nazwa}" Header="Nazwa"/>
        <GridViewColumn  DisplayMemberBinding="{Binding Path = Metoda}" Header="Metoda badawcza"/>
        <GridViewColumn  DisplayMemberBinding="{Binding Path = Jednostka}" Header="Jednostka"/>
    </GridView>
</ListView.View>





列表视图是填充了linq-to-sql:





The listview is filled with a linq-to-sql:

public class Dane
{
    public string ID { get; set; }
    public string Nazwa { get; set; }
    public string Metoda { get; set; }
    public string Jednostka { get; set; }
}

back_clasesDataContext dc = new back_clasesDataContext();
var dane = (from k in dc.tblDanes
    where (k._1 == 2 && k.Aktywne == true)
        select new Dane { ID = k.Id_Osoby, Nazwa = k.Nazwa, Metoda = k.Metoda, Jednostka = k.Jednostka }).ToList();
dgDane.ItemsSource = dane;





我希望从这个多列列表视图中获取ID形式的选定值。 />
先谢谢。



我尝试过:



当我的列表视图中选择了多个项目时,我会尝试获取ID:





I want to get ID form selected values from this multi-column listview.
Thanks in advance.

What I have tried:

And when multiple items are selected on my listview, I try to get the ID:

foreach (DataRowView objDataRowView in dgDane.SelectedItems)
{
    MessageBox.Show(objDataRowView["ID"].ToString());
}





我收到错误:





I getting an error:

An unhandled exception of type 'System.InvalidCastException' occurred in crl.exe
Additional information: Additional information: Unable to cast object of type 'crl.Dane' to type 'System.Data.DataRowView'.

推荐答案

foreach (var selectedDane in dgDane.SelectedItems)
{
  MessageBox.Show(selectedDane.ID);
}



因此,如果只需要收集或修改 Dane 个实例, ,他们已经在那里了!



编辑:MTH

哎呀,我忘了SelectedItems不是特定于类型的。

两种解决方法:


So if all you need to do it to collect or modify the Dane instances, themselves, they're already there!

MTH
Oops, I forgot that SelectedItems is not type-specific.
Two ways to fix it:

// this will depend on: using System.Linq;
foreach (var selectedDane in dgDane.SelectedItems.Cast<Dane>())
{
  MessageBox.Show(selectedDane.ID);
}






or

foreach (var sel in dgDane.SelectedItems)
{
  Dane selectedDane = (Dane)sel;
  MessageBox.Show(selectedDane.ID);
}


这篇关于如何从多个选定的列表视图中获取选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 14:40