前言
我们想实现这样一个功能列表中点击某一项就在该项的位置显示一个悬浮框显示内容。
主要解决思路就是获取按钮相对于列表的偏移位置,调整悬浮框的位置。
具体代码
列表模板
这里主要是添加一个按钮触发点击事件
代码语言:javascript复制<Window.Resources>
<DataTemplate x:Key="TjItemDt"
DataType="{x:Type page:VoteTj}">
<Grid Margin="0 20 0 0">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="Auto"></RowDefinition>
</Grid.RowDefinitions>
<Grid>
<TextBlock VerticalAlignment="Center"
HorizontalAlignment="Left"
Text="{Binding OptionStr}"
Style="{StaticResource CommonTb}">
</TextBlock>
<StackPanel Orientation="Horizontal"
VerticalAlignment="Center"
HorizontalAlignment="Right">
<TextBlock VerticalAlignment="Center"
HorizontalAlignment="Left"
Text="{Binding Num}"
Foreground="{StaticResource PrimaryColorBrush}"
Style="{StaticResource CommonTb}">
</TextBlock>
<TextBlock VerticalAlignment="Center"
HorizontalAlignment="Left"
Foreground="{StaticResource PrimaryColorBrush}"
Text="票"
Style="{StaticResource CommonTb}">
</TextBlock>
<TextBlock VerticalAlignment="Center"
HorizontalAlignment="Left"
Margin="10 0 0 0"
Foreground="#798CB5"
Text="{Binding SubmitRate}"
Style="{StaticResource CommonTb}">
</TextBlock>
</StackPanel>
</Grid>
<Grid Grid.Row="1">
<ProgressBar Value="{Binding Num}"
Margin="0 2 0 0"
Maximum="{Binding NumTotal}"
Foreground="#339DFF"
Background="#EAF5FF"
Height="24"
Style="{StaticResource HorRoundedPbStyle}"
Orientation="Horizontal"
BorderThickness="0">
</ProgressBar>
<Button Background="Transparent"
Click="TjItemClick">
</Button>
</Grid>
</Grid>
</DataTemplate>
</Window.Resources>
页面
代码语言:javascript复制<Grid>
<ScrollViewer Name="TjSv"
Padding="200 -20 200 20">
<ItemsControl ItemsSource="{Binding TjList}"
ItemTemplate="{StaticResource TjItemDt}">
</ItemsControl>
</ScrollViewer>
<Border Width="400"
Height="100"
CornerRadius="8"
Background="White"
BorderThickness="1"
BorderBrush="#eee"
HorizontalAlignment="Center"
Visibility="Hidden"
VerticalAlignment="Top"
Padding="10"
Name="ShowArea">
<TextBlock Text="这是悬浮的内容"
FontSize="16">
</TextBlock>
</Border>
</Grid>
代码
这里悬浮层居中,所以只用设置Y轴方向的偏移即可。
另外注意判断别让悬浮框超出显示的范围。
代码语言:javascript复制private void TjItemClick(object sender, RoutedEventArgs e)
{
if (!(sender is Button btn))
{
return;
}
Point relativeLocation = btn.TranslatePoint(new Point(0, 0), TjSv);
double relativeLocationY = relativeLocation.Y 12;
//防止悬浮框超出列表区域
if (relativeLocationY ShowArea.Height > TjSv.ActualHeight)
{
relativeLocationY = TjSv.ActualHeight - ShowArea.Height;
}
ShowArea.Margin = new Thickness(
0,
relativeLocationY,
0,
0
);
ShowArea.Visibility = Visibility.Visible;
}