WPF自定义Popup位置

popup的位置是通过属性Placement 来控制的,如果想自己定义popup位置,那么需要将Placement 属性设置为Custom。

当 Placement 属性设置为时 Custom ,将 Popup 调用已定义的委托实例 CustomPopupPlacementCallback 。 此委托返回一组可能的点,这些点相对于目标区域的左上角和左上角 Popup 。 Popup放置在提供最佳可见性的点上。

 

下面是用法:

xaml代码

1
2
3
4
5
6
7
8
<Popup Name="popup1" 
        PlacementTarget ="{Binding ElementName=myButton}"
        Placement="Custom">
  <TextBlock Height="60" Width="200"
             Background="LightGray"
             TextWrapping="Wrap">Popup positioned by using
  CustomPopupPlacement callback delegate</TextBlock>
</Popup>

C#代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
popup1.CustomPopupPlacementCallback = new CustomPopupPlacementCallback(placePopup);public CustomPopupPlacement[] placePopup(Size popupSize,
                                           Size targetSize,
                                           Point offset)
{
    CustomPopupPlacement placement1 =
       new CustomPopupPlacement(new Point(-50, 100), PopupPrimaryAxis.Vertical);
 
    CustomPopupPlacement placement2 =
        new CustomPopupPlacement(new Point(10, 20), PopupPrimaryAxis.Horizontal);
 
    CustomPopupPlacement[] ttplaces =
            new CustomPopupPlacement[] { placement1, placement2 };
    return ttplaces;
}

 

来看一下placePopup方法的参数offset

offset是popup位置的坐标,默认为(0,0),下面的纵向和横向偏移量是根据此点坐标来说的,如果要指定popup的起始坐标,应设置popup的VerticalOffset和HorizontalOffset

比如说要设置为鼠标点的位置为默认起始点,则应该设置:

1
2
3
4
Point mousePoint = Mouse.GetPosition(canvas);//比如canvas为所在画布
 
popup.VerticalOffset = mousePoint.Y;
popup.HorizontalOffset = mousePoint.X;

  

 

posted @   刺眼  阅读(4596)  评论(1编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示