从选定项目中获取价值的麻烦

时间:2013-10-06 17:23:50

标签: c# wpf listview

我想在ListView中获取SelectedItems值,但它不起作用!

选择一个项目时我没有问题,但我想在扩展模式下工作,因此它会显示任何选定的项目。

我的代码是:

    List<Fnamelist> familylist = new List<Fnamelist>();
    public class Fnamelist
    {

        public Fnamelist(string fname)
        {
            this.Fname = fname;

        }
        private string fname = string.Empty;
        public string Fname
        {
            get { return fname; }
            set { fname = value; }
        }

    }


    private void button1_Click(object sender, RoutedEventArgs e)
    {

       MessageBox.Show(((Fnamelist)listView1.SelectedItems).Fname.ToString()); 
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        familylist.Add(new Fnamelist("mike"));
        familylist.Add(new Fnamelist("john"));
        familylist.Add(new Fnamelist("melon"));
        familylist.Add(new Fnamelist("bab"));
        listView1.ItemsSource = familylist;
        listView1.Items.Refresh();
    }  

xaml:

    <Button Content="show" Height="23" HorizontalAlignment="Left" Margin="331,79,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    <ListView Height="129" HorizontalAlignment="Left" Margin="20,23,0,0" Name="listView1" VerticalAlignment="Top" Width="291">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding Path=Fname}"/>
            </GridView>
        </ListView.View>
    </ListView>

当我点击显示按钮时,它会出错:

Unable to cast object of type 'System.Windows.Controls.SelectedItemCollection' to type 'Fnamelist'.

问题是什么?

1 个答案:

答案 0 :(得分:5)

button1_Click事件处理程序中的代码正在尝试显示单个项目的Fname,其中listView1.SelectedItems是项目集合。

您可以显示第一个选定项目:

MessageBox.Show(((Fnamelist)listView1.SelectedItems[0]).Fname);

或迭代所选项目集合并在内部执行任何操作,例如MessageBox

foreach (var item in listview1.SelectedItems)
{
      string fname = ((Fnamelist)item).Fname;
      MessageBox.Show(fname);
}

在旁注上,您可以删除ToString()来电。由于Fname已经是一个字符串,所以它是冗余的。