效果图:使弹出的列表框紧随在单元格的下边缘。

WPF学习笔记(2):准确定位弹出窗

第一次,尝试在XAML中设置Popup的定位方式:Placement="Mouse"。基本能够定位,但当在输入前移动鼠标,列表框就会随鼠标位置显示,偏离了预定位置。

第二次,尝试在XAML中设置Popup的定位目标:PlacementTarget="{Binding ElementName=txtAcctName}">。但由于TextBox位于DataGridTemplateColumn中,不起作用。

第三次,改变思路,通过获取TextBox的位置后,再以此设置Popup的位置,成功解决问题。定位目标设置为DataGrid,定位方式设置为Relative(以目标控件的左上角为原点),代码如下:

XAML代码:

<Popup Name="popAcct" StaysOpen="False" Placement="Relative"  MaxHeight="500" PlacementTarget="{Binding ElementName=dgVoucher}">

C#代码: 

private void txtAcctName_TextChanged(object sender, TextChangedEventArgs e)
{
    //定位popup的位置,使之位于当前单元格的下边缘
    TextBox txtAcctName = sender as TextBox;
    Point position = txtAcctName.TranslatePoint(new Point(), dgVoucher); //获取当前单元格的位置,dgVoucher为DataGrid名称
popAcct.HorizontalOffset = position.X; //设置横坐标偏移量
popAcct.VerticalOffset = position.Y + txtAcctName.ActualHeight; //纵坐标偏移量+行高(文本框实际显示高度)
}

 

相关文章:

  • 2021-08-22
  • 2022-12-23
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
  • 2021-09-19
  • 2022-01-29
猜你喜欢
  • 2022-01-20
  • 2022-12-23
  • 2021-06-03
  • 2021-07-09
  • 2022-02-18
相关资源
相似解决方案