【问题标题】:UWP - get first child of GridviewUWP - 获取 Gridview 的第一个孩子
【发布时间】:2018-07-24 13:51:23
【问题描述】:
<GridView x:Name="MainGridStations" ItemsSource="{x:Bind Stations}" IsItemClickEnabled="True" ItemClick="GridView_ItemClick">
            <GridView.ItemTemplate>
                <DataTemplate x:DataType="local:Station">
                    <Grid x:Name="WantToSelectByCode">
                        <Grid Background="White" HorizontalAlignment="Center" Width="300" Height="200" VerticalAlignment="Center">
                              <Grid Background="#e4f0fc" Height="65" VerticalAlignment="Bottom" Opacity="0.8">
                                <TextBlock x:Name="StationName" Text="{Binding Name}" FontWeight="Bold" Foreground="#2c9a8b" HorizontalAlignment="Center" />
                            </Grid>
                        </Grid>
                    </Grid>
                </DataTemplate>
            </GridView.ItemTemplate>
</GridView>

我正在尝试通过动态填充的 gridview 的索引来选择一个孩子,但我尝试过的总是返回 null。

例如第一个孩子是这样的:

var container = MainGridStations.ContainerFromIndex(0);

var presenter = VisualTreeHelper.GetChild(container, 0) as GridViewItem;

我在这里做错了什么?

【问题讨论】:

    标签: c# xaml gridview datagridview uwp


    【解决方案1】:

    您可以直接从ItemsControl.ContainerFromIndex(Int32)方法中获取对应的GridViewItem,无需再次使用VisualTreeHelper获取。

    var container = MainGridStations.ContainerFromIndex(0);
    GridViewItem gridViewItem= container as GridViewItem;
    gridViewItem.Background = new SolidColorBrush(Colors.Red);
    

    container 是从索引中得到的对应的GridViewItem

    注意:由于你的内部 Grid 有一个Background="White" 属性配置,你可以删除代码以更明显地看到效果,使用我上面的代码更改gridViewItem.Background

    ---更新---

    您必须在加载项目后获取GridViewItem。您可以在GridView_ItemClick 事件处理程序或页面加载的事件处理程序中尝试代码。还要注意我上面的注释,为了获得更明显的效果,请删除上面xaml代码中的Background="White"

    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        var container = MainGridStations.ContainerFromIndex(0);
        GridViewItem gridViewItem = container as GridViewItem;
        gridViewItem.Background = new SolidColorBrush(Colors.Green);
    }
    
    //get the item here
    private void GridView_ItemClick(object sender, ItemClickEventArgs e)
    {
        var container = MainGridStations.ContainerFromIndex(0);
        GridViewItem gridViewItem= container as GridViewItem;
        gridViewItem.Background = new SolidColorBrush(Colors.Red);
        //var presenter = VisualTreeHelper.GetChild(container, 0) as GridViewItem;
    }
    

    【讨论】:

    • 我也试过了。由于某种原因,它总是返回 null。
    猜你喜欢
    • 1970-01-01
    • 2017-09-21
    • 2017-03-11
    • 1970-01-01
    • 2017-06-23
    • 2012-02-09
    • 2011-06-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多