c# - 通过gridview selecteditem查找和修改图像控件

时间:2017-03-17 17:39:03

标签: c# gridview uwp

当在uwp中引发click事件时,我需要在gridview datatemplate中更改Image控件的源代码。当我点击汽车图像时,需要修改此图像并显示品牌标识。我成功完成了那段代码:

   <controls:AdaptiveGridView x:Name="AdaptiveGridViewControl"
                              animations:ReorderGridAnimation.Duration="350"
                              Margin="0,12,0,0"
                              ItemHeight="200"
                              DesiredWidth="200"
                              SelectionMode="Single"
                              IsItemClickEnabled="True"
                              ItemClick="GridView_ItemClick"
                              >

        <controls:AdaptiveGridView.ItemTemplate>
            <DataTemplate x:DataType="data:MyData">
                        <StackPanel Orientation="Horizontal">
                            <controls:ImageEx x:Name="ImageExControl"
                                      MaxHeight="200"
                                      IsCacheEnabled="True"
                                      Source="{x:Bind carsPictures}"
                                      Stretch="Fill"
                                      PlaceholderSource="/Assets/placeholder_cover.jpg"
                                      PlaceholderStretch="Uniform"/>
                        </StackPanel>
            </DataTemplate>
        </controls:AdaptiveGridView.ItemTemplate>
    </controls:AdaptiveGridView>

感谢帖子:How to access a Control inside the data template in C# Metro UI in the code behind, 我可以使用FindChildControl(DependencyObject控件,字符串ctrlName)方法。

在代码背后:

 private void GridView_ItemClick(object sender, ItemClickEventArgs e)
    {
        var newData = (MyData)e.ClickedItem;

        ImageEx ex = FindChildControl<ImageEx>(this, "ImageExControl") as ImageEx;
        ex.Source = newData.brandLogo;
    }

问题是这个gridview包含30个汽车图片,并且在引发点击事件时只修改了第一个Image控件。我不知道如何使用AdaptiveGridView.SelectedItem来更改单击的Image控件。

1 个答案:

答案 0 :(得分:0)

您需要获取GridViewItem Clicked,以便您可以更改Clicked Item的图像。将您的ItemClick活动更改为以下内容。

private void GridView_ItemClick(object sender, ItemClickEventArgs e)
{
    GridViewItem item = myGridView.ContainerFromItem(e.ClickedItem) as GridViewItem;
    MyData newData = (MyData)e.ClickedItem;
    ImageEx ex = FindChildControl<ImageEx>(item, "ImageExControl") as ImageEx;
    ex.Source = newData.brandLogo;
}

希望这有助于。