Search code examples
xamluwpuwp-xamlwinui

UWP WinUI2 xaml How to access element within DataTemplate in code behind


I have following xaml code

<DataTemplate x:Key="ImageTextTemplate" x:DataType="local1:CustomDataObject">
    <Grid AutomationProperties.Name="{x:Bind Title}" Width="280"
            PointerEntered="Grid_PointerEntered"
            PointerExited="Grid_PointerExited">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Image Source="{x:Bind ImageLocation}" Height="100" Stretch="Fill" VerticalAlignment="Top"/>
        <StackPanel Grid.Column="1" Margin="8,0,0,8">
            <TextBlock Text="{x:Bind Title}" Style="{ThemeResource SubtitleTextBlockStyle}" Margin="0,0,0,8"/>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{x:Bind Views}" Style="{ThemeResource CaptionTextBlockStyle}"/>
                <TextBlock Text=" Views " Style="{ThemeResource CaptionTextBlockStyle}"/>
            </StackPanel>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{x:Bind Likes}" Style="{ThemeResource CaptionTextBlockStyle}" />
                <TextBlock Text=" Likes" Style="{ThemeResource CaptionTextBlockStyle}"/>
            </StackPanel>
        </StackPanel>
        <ToolTipService.ToolTip>
            <ToolTip x:Name="MyToolTip" Content="This is my tooltip" />
        </ToolTipService.ToolTip>
    </Grid>
</DataTemplate>

I want to access the tooltip element in code behind. But when I do following, it is giving me error.

Error: The name 'MyToolTip' does not exist in the current context

private void Grid_PointerExited(object sender, Windows.UI.Xaml.Input.PointerRoutedEventArgs e)
{
    var gridViewItem = sender as GridViewItem;
    if (!gridViewItem.IsEnabled)
    {
        ToolTipService.SetToolTip(gridViewItem, null);
        MyToolTip.IsOpen = true;
    }
}

I am trying to show the tooltip on disabled GridViewItem. The code is from the WinUI 2 Gallery samples on github.


Solution

  • You can't cast the sender argument of an event handler attached to a Grid to anything else than a Grid.

    Once you have the reference to the Grid, you could access its ToolTip using the attached property:

    private void Grid_PointerExited(object sender, PointerRoutedEventArgs e)
    {
        Grid grid = (Grid)sender;
        ToolTip MyToolTip = ToolTipService.GetToolTip(grid) as ToolTip;
        if (MyToolTip != null)
            MyToolTip.IsOpen = true;
    }