DataContext of DataTemplate in ToolTip Style in WP

2019-07-14 07:20发布

问题:

I can't seem to find the right DataContext for the Grid in the ToolTipStyle Style. Just a blank ToolTip appears.

<Window.Resources>
    <DataTemplate x:Key="ListTemplate">
        <StackPanel>
            <Grid>
                <TextBlock Text="{Binding Path=Name}">
                    <TextBlock.ToolTip>
                        <ToolTip Style="{StaticResource ToolTipStyle}" />
                    </TextBlock.ToolTip>
                </TextBlock>
            </Grid>
        </StackPanel>
    </DataTemplate>

    <Style TargetType="ToolTip" x:Key="ToolTipStyle">
        <Setter Property="ContentTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Grid>
                        <TextBlock Text="{Binding Path=Description}" />
                    </Grid>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Windows.Resources>

<ListBox ItemTemplate="{StaticResource ListTemplate}" />

回答1:

Tooltips /Popups seem to exist outside of the visual tree. I see a lot of people bind to the PlacementTarget property to get back.

DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}"

<DataTemplate x:Key="ListTemplate">
    <StackPanel>
        <Grid>
            <TextBlock>
                <TextBlock.ToolTip>
                    <ToolTip DataContext="{Binding Path=PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}" Text="{Binding Path=Name}" Style="{StaticResource ToolTipStyle}" />
                </TextBlock.ToolTip>
            </TextBlock>
        </Grid>
    </StackPanel>
</DataTemplate>