如何确定gridview中单击的项目

时间:2013-04-05 12:51:29

标签: c# xaml gridview microsoft-metro

我使用此XAML代码创建gridview并向其添加项目:

<Grid x:Name="MainStack" HorizontalAlignment="Left" Height="628" Grid.Row="1" VerticalAlignment="Top" Width="1366">
        <GridView
        x:Name="itemGridView"
        AutomationProperties.AutomationId="ItemsGridView"
        AutomationProperties.Name="Items"
        TabIndex="1"
            Grid.RowSpan="2"
        Padding="130,42,116,46"
        ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
        SelectionMode="None"
        IsSwipeEnabled="false"
        IsItemClickEnabled="True"
        Background="#FFFB0404" Margin="0,0,0,0" RenderTransformOrigin="0.489,0.503" ItemClick="MainPage_Click">
            <x:String>Item 1</x:String>
            <x:String>Item 2</x:String>
            <x:String>Item 3</x:String>
            <x:String>Item 4</x:String>
            <x:String>Item 5</x:String>
            <x:String>Item 6</x:String>
            <x:String>Item 7</x:String>
            <x:String>Item 8</x:String>
        </GridView>
    </Grid>

然后我尝试使用这个C#代码

 private void MainPage_Click(object sender, ItemClickEventArgs e)
    {
        string output = e.ClickedItem.ToString();
        int ClickValue = Convert.ToInt32(output);
        if (ClickValue == 0)
        {
            this.Frame.Navigate(typeof(ItemsPageRSS));
        }
    }

使应用在单击第一个项目时导航到某个页面,但是它出错了。

如果有人能告诉我如何隔离每个iem并为每个iem添加单独的点击事件以及如何通过向项目添加标题,字幕和图像来自定义gridview项目。 提前谢谢。

1 个答案:

答案 0 :(得分:7)

如果您无法理解MSDN示例,我将在此给您一个简单的示例。只需创建新项目并粘贴整个代码。

XAML

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <GridView
        x:Name="itemGridView"
        ItemTemplate="{StaticResource Standard250x250ItemTemplate}"
        SelectionMode="None"
        IsItemClickEnabled="True"
        Background="#FFFB0404" 
        ItemClick="MainPage_Click"/>
</Grid>

C#

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    var gvData = new ObservableCollection<MyData>();
    for (int i = 0; i < 8; i++)
    {
        gvData.Add(new MyData
        {
            ID = i,
            Image = new BitmapImage(new Uri("ms-appx:///Assets/Logo.png")), //You can add any image
            Title = "Title " + i,
            Subtitle = "Subtitle " + i
        });
    }
    itemGridView.ItemsSource = gvData;
}

private void MainPage_Click(object sender, ItemClickEventArgs e)
{
    MyData output = e.ClickedItem as MyData;
    int ClickValue = output.ID;
    if (ClickValue == 0)
    {
        this.Frame.Navigate(typeof(ItemsPageRSS));
        //TODO : Do whatever you want
    }

    //.....
    //TODO : Do operations for other items as well.
}

您可以在MyData(XAML Page)类的范围之外创建MainPage类。

public class MyData
{
    public int ID { get; set; }
    public ImageSource Image { get; set; }
    public string Title { get; set; }
    public string Subtitle { get; set; }
}