ravi kumar
ravi kumar

Reputation: 1620

UWP VisualTreeHelper.GetParent() returns null

I have a ContentDialog which has a ListView. This ListView's DataTemplate Contains a Grid and this Grid has a Button. The code goes like this:

<ContentDialog x:Name="DownloadListDialog" x:FieldModifier="public" Grid.Column="1">
    <ListView Name="AssetsListView" IsItemClickEnabled="False" Grid.Row="1" SelectionMode="Single" MaxHeight="500" ItemsSource="{x:Bind _viewModel.Assets, Mode=OneWay}">
        <ListView.ItemContainerStyle>
            <Style TargetType="ListViewItem">
                       ...
                       ...
                    </Style>
        </ListView.ItemContainerStyle>
        <ListView.ItemTemplate>
            <DataTemplate x:DataType="viewModel:AssetViewModel">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*"/>
                        <ColumnDefinition Width="Auto"/>
                    </Grid.ColumnDefinitions>
                    <StackPanel>
                        <TextBlock Text="{x:Bind name}"/>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{x:Bind lblFileSize}"/>
                            <TextBlock Text="{x:Bind contentSize, Mode=OneWay}"/>
                            <TextBlock Text="{x:Bind contentUrl}" Visibility="Collapsed"/>
                        </StackPanel>
                    </StackPanel>
                    <Button Content="Download" Click="Button_Click" HorizontalAlignment="Right" Grid.Column="1"/>
                </Grid>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentDialog>

Here's my Button Click event handler:

private async void Button_Click(object sender, RoutedEventArgs e)
{
    var grid = VisualTreeHelper.GetParent(sender as Button) as Grid;
    ...
    ...
}

The problem is that the variable VisualTreeHelper.GetParent(sender as Button) as Grid always returns null on my PC. But this same code when I deploy on my mobile works perfectly fine (i.e, variable grid gets assigned the correct value).

UPDATE: Here's my Live Visual Tree and it confirms that the button has a parent grid. Image

App min version: build 14393 App target version: Build 15063 PC windows version: Build 17134 (version 1803)

Note: I've tried changing the App target version to 1803 but the problem remains.

Upvotes: 15

Views: 1938

Answers (1)

Niels de Schrijver
Niels de Schrijver

Reputation: 335

As I understand from a different question there are several ways to get the parent of the VisualTreeHelper. Could it be that on your mobile or PC for that matter in the background different things are loaded so that the location of where you can find the grid object changes.

You could check this answer as a reference of what I stated above: FrameworkElement.Parent and VisualtreeHelper.GetParent behaves differently

Upvotes: 4

Related Questions