从ListView中的选定项目获取数据

时间:2015-02-18 09:33:11

标签: c# xaml listview listviewitem

我有以下C#代码为列表视图生成项目:

//function that generated items for list view

 results = //An array

                    foreach (var item in results)
                    {
                        var nameStr = item.FirstName + " " + item.LastName;
                        var descriptionStr = item.Email;
                        IconTextGrid.Items.Add(new { Name = nameStr, Description = descriptionStr });

                }

和XAML:

<Page.Resources>
    <DataTemplate x:Key="IconTextDataTemplate">
        <StackPanel Orientation="Horizontal" Width="220" Height="60" Background="#FF7CC6FF">

            <StackPanel Orientation="Vertical" VerticalAlignment="Center">
                <TextBlock Text="{Binding Name}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
                <TextBlock Text="{Binding Description}" Margin="10,0,0,0" Width="170" Height="20" TextTrimming="WordEllipsis"/>
            </StackPanel>
        </StackPanel>
    </DataTemplate>
</Page.Resources>

<ListView x:Name="IconTextGrid"  SelectionMode="Multiple" ItemTemplate="{StaticResource IconTextDataTemplate}" Height="400"  Grid.Row="5" Margin="40,20,40,10" HorizontalAlignment="Stretch" Foreground="White" SelectionChanged="IconTextGrid_SelectionChanged">
                    <ListView.ItemsPanel>
                        <ItemsPanelTemplate>
                            <ItemsWrapGrid MaximumRowsOrColumns="6"/>
                        </ItemsPanelTemplate>
                    </ListView.ItemsPanel>
                </ListView>

private void SendRequests_Click(object sender, RoutedEventArgs e)
        {
            string emailAdress;
            for (int i = 0; i < IconTextGrid.SelectedItems.Count; i++)
            {
                //I need to get the description of the selected items
            }
        }

我的问题是如何在生成的项目中获取Description字段的值? 感谢

2 个答案:

答案 0 :(得分:0)

您可以像这样创建自定义类型:

class MyType
{
     string Name { get; set; }
     string Description { get; set; }
}

然后将您的代码更改为:

IconTextGrid.Items.Add(new MyType{ Name = nameStr, Description = descriptionStr });

现在你可以得到描述:

for (int i = 0; i < IconTextGrid.SelectedItems.Count; i++)
        {
            var item = (MyType)IconTextGrid.SelectedItems[i];
            string description = item.Description;
        }

答案 1 :(得分:0)

您使用的是列表框中项目的匿名类型:

IconTextGrid.Items.Add(new { Name = nameStr, Description = descriptionStr });

你应该宣布一个班级:

public class MyItem
{
    public string Name { get; set; }
    public string Description { get; set; }
}

并改为使用此类:

IconTextGrid.Items.Add(new MyItem { Name = nameStr, Description = descriptionStr });

您可以获得SelectedItem并将其投放到MyItem