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; |
分类:
WPF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 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语句:使用策略模式优化代码结构