网站首页 全球最实用的IT互联网站!

人工智能P2P分享Wind搜索发布信息网站地图标签大全

当前位置:诺佳网 > 软件工程 > 后端开发 > .Net >

TextBoxPopupBehavior控件

时间:2025-07-19 20:47

人气:

作者:admin

标签:

导读:功能说明 一个用于 WPF TextBox 的附加行为,实现 TextBox 与 Popup 控件的联动效果: 自动弹出/关闭: TextBox 获得焦点时自动打开关联的 Popup TextBox 失去焦点时自动关闭关联的 Popup 点击外部...

功能说明

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

  1. 自动弹出/关闭

    • TextBox 获得焦点时自动打开关联的 Popup
    • TextBox 失去焦点时自动关闭关联的 Popup
  2. 点击外部关闭

    • 点击 TextBox 和 Popup 外部区域时关闭 Popup
  3. 焦点状态处理

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

核心代码解析

        // 解决在 TextBox 外其他地方点击时,仅关闭 Popup,但是 TextBox 还是 Focused 状态,导致再点击进来时不会触发弹出 Popup
        private void AssociatedObject_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
            if (AssociatedObject?.IsFocused == true && Popup != null && !Popup.IsOpen) {
                Popup.IsOpen = true;
            }
        }

        private void Window_PreviewMouseDown(object sender, System.Windows.Input.MouseButtonEventArgs e) {
            if (Popup == null || !Popup.IsOpen || AssociatedObject == null || _parentWindow == null) { return; }

            Point position = e.GetPosition(null);
            Rect textBoxRect = new Rect(AssociatedObject.TranslatePoint(new Point(0, 0), _parentWindow), AssociatedObject.RenderSize);
            Rect popupRect = new Rect(Popup.TranslatePoint(new Point(0, 0), _parentWindow), Popup.RenderSize);
            if (!textBoxRect.Contains(position) && !popupRect.Contains(position)) {
                Popup.SetCurrentValue(Popup.IsOpenProperty, false);
            }
        }

使用方法

<TextBox x:Name="SearchBox"
         Width="400"
         Height="30"
         Text="{Binding ElementName=list, Path=SelectedItem.Content}">
    <hc:Interaction.Behaviors>
        <controls:TextBoxPopupBehavior Popup="{Binding ElementName=SuggestionsPopup}" />
    </hc:Interaction.Behaviors>
</TextBox>

<Popup x:Name="SuggestionsPopup"
       Placement="Bottom"
       PlacementTarget="{Binding ElementName=SearchBox}"
       StaysOpen="True">
    <Border Background="White"
            BorderBrush="Gray"
            BorderThickness="1">
        <ListBox x:Name="list"
                 Width="200"
                 Height="150">
            <ListBoxItem>选项1</ListBoxItem>
            <ListBoxItem>选项2</ListBoxItem>
            <ListBoxItem>选项3</ListBoxItem>
        </ListBox>
    </Border>
</Popup>

注意事项

  • 确保 Popup 的 PlacementTarget 正确绑定
  • 在 MVVM 模式下可通过绑定设置 Popup 属性
  • 控件卸载时会自动清理事件监听

文章作者:Memento
博客地址:http://www.cnblogs.com/Memento/
版权声明:Memento所有文章遵循创作共用版权协议,要求署名、非商业、保持一致。在满足创作共用版权协议的基础上可以转载,但请以超链接形式注明出处。
温馨提示:以上内容整理于网络,仅供参考,如果对您有帮助,留下您的阅读感言吧!
相关阅读
本类排行
相关标签
本类推荐

CPU | 内存 | 硬盘 | 显卡 | 显示器 | 主板 | 电源 | 键鼠 | 网站地图

Copyright © 2025-2035 诺佳网 版权所有 备案号:赣ICP备2025066733号
本站资料均来源互联网收集整理,作品版权归作者所有,如果侵犯了您的版权,请跟我们联系。

关注微信