TextBoxPopupBehavior控件

[复制链接]
发表于 2025-7-20 02:24:06 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
功能说明

一个用于 WPF TextBox 的附加举动,实现 TextBox 与 Popup 控件的联动结果:

  • 自动弹出/关闭:

    • TextBox 获得核心时自动打开关联的 Popup
    • TextBox 失去核心时自动关闭关联的 Popup

  • 点击外部关闭:

    • 点击 TextBox 和 Popup 外部区域时关闭 Popup

  • 核心状态处置惩罚:

    • 解决 TextBox 保持核心但 Popup 关闭后的重新触发问题

核心代码解析
  1.         // 解决在 TextBox 外其他地方点击时,仅关闭 Popup,但是 TextBox 还是 Focused 状态,导致再点击进来时不会触发弹出 Popup
  2.         private void AssociatedObject_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
  3.             if (AssociatedObject?.IsFocused == true && Popup != null && !Popup.IsOpen) {
  4.                 Popup.IsOpen = true;
  5.             }
  6.         }
  7.         private void Window_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
  8.             if (Popup == null || !Popup.IsOpen || AssociatedObject == null || _parentWindow == null) { return; }
  9.             Point position = e.GetPosition(null);
  10.             Rect textBoxRect = new Rect(AssociatedObject.TranslatePoint(new Point(0, 0), _parentWindow), AssociatedObject.RenderSize);
  11.             Rect popupRect = new Rect(Popup.TranslatePoint(new Point(0, 0), _parentWindow), Popup.RenderSize);
  12.             if (!textBoxRect.Contains(position) && !popupRect.Contains(position)) {
  13.                 Popup.SetCurrentValue(Popup.IsOpenProperty, false);
  14.             }
  15.         }
复制代码
使用方法
  1. <TextBox x:Name="SearchBox"
  2.          Width="400"
  3.          Height="30"
  4.          Text="{Binding ElementName=list, Path=SelectedItem.Content}">
  5.     <hc:Interaction.Behaviors>
  6.         <controls:TextBoxPopupBehavior Popup="{Binding ElementName=SuggestionsPopup}" />
  7.     </hc:Interaction.Behaviors>
  8. </TextBox>
  9. <Popup x:Name="SuggestionsPopup"
  10.        Placement="Bottom"
  11.        PlacementTarget="{Binding ElementName=SearchBox}"
  12.        StaysOpen="True">
  13.     <Border Background="White"
  14.             BorderBrush="Gray"
  15.             BorderThickness="1">
  16.         <ListBox x:Name="list"
  17.                  Width="200"
  18.                  Height="150">
  19.             <ListBoxItem>选项1</ListBoxItem>
  20.             <ListBoxItem>选项2</ListBoxItem>
  21.             <ListBoxItem>选项3</ListBoxItem>
  22.         </ListBox>
  23.     </Border>
  24. </Popup>
复制代码
留意事项


  • 确保 Popup 的 PlacementTarget 正确绑定
  • 在 MVVM 模式下可通过绑定设置 Popup 属性
  • 控件卸载时会自动清理事件监听
文章作者:Memento
博客地址:
版权声明:Memento所有文章遵循创作共用版权协议,要求署名、非贸易、保持一致。在满足创作共用版权协议的基础上可以转载,但请以超链接情势注明出处。       
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表