DataContext of DataTemplate in ToolTip Style in WP

2019-07-14 07:45发布

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条回答
时光不老,我们不散
2楼-- · 2019-07-14 08:14

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>
查看更多
登录 后发表回答