wpf popup style绑定到父级元素

思路

  • 通过ToolTip的PlacementTarget找到它定位的元素,此元素在视觉内
  • 利用定位元素的Tag绑定到它的父级元素
  <Style x:Key="ListBoxStyle" TargetType="{x:Type ListBox}">
     <Setter Property="ItemTemplate">
        <Setter.Value>
           <DataTemplate>
              <StackPanel
                 x:Name="mySt"
                 Background="Transparent"
                 Orientation="Horizontal"
                 Tag="{Binding RelativeSource={RelativeSource AncestorType=ListBox}}">
                 <TextBlock Background="Red" Text="{Binding}" />

                 <!--  绑定到listbox的宽度属性  -->
                 <TextBlock Background="Gray" Text="{Binding ActualWidth, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}" />

                 <FrameworkElement.ToolTip>
                    <ToolTip>
                       <Border
                          Width="300"
                          Height="100"
                          Background="Green"
                          BorderThickness="2">
                          <StackPanel>
                             <!--  这里由于不与ListBox在同一个视觉树中,所以ListBox不是它的父元素,想绑定其属性就比较麻烦了  -->
                             <!--<TextBlock Background="Gray" Text="{Binding ActualWidth}" />-->

                             <!--  可以利用popup的PlacementTarget特性来找到ToolTip的停靠对象,当前是mySt,但是如果要继续向上查找就比较麻烦了  -->
                             <TextBlock Background="Red" Text="{Binding RelativeSource={RelativeSource AncestorType=ToolTip}, Path=PlacementTarget.Tag.Name}" />

                             <!--  绑定到VM的属性,当前vm是一个stirng类型  -->
                             <!--<TextBlock Background="Gray" Text="{Binding Length}" />-->
                          </StackPanel>
                       </Border>
                    </ToolTip>
                 </FrameworkElement.ToolTip>
              </StackPanel>
           </DataTemplate>
        </Setter.Value>
     </Setter>
  </Style>

但是我发现这个操作,如果要让ToolTip绑定到一个是否可见的属性有点问题(好像是显示之后才绑定?而我需要它一开始就不显示)

直接加一个透明border,让是否显示的属性绑定到这个border上,border不见了,ToolTip自然也就不显示了

posted @ 2025-06-21 19:59  trykle  阅读(12)  评论(0)    收藏  举报