c# - 如何使 WPF Combobox 的下拉列表保持打开和放置

标签 c# .net wpf combobox drop-down-menu

我想让组合框可编辑,并且下拉列表保持打开状态。

目前设置了这些属性:

IsEditable="True" IsDropDownOpen="True" StaysOpenOnEdit="True" 

每当用户单击输入文本框或焦点更改为其他控件时,dorpdown 将关闭。因此,我更新了模板(WPF Theme 中包含的模板:BureauBlue)以在这种特殊情况下使 Popup IsOpen="true" 使下拉列表保持打开状态,但是现在,当用户拖动并移动窗口的位置时,下拉菜单将不会自动更新其位置并保持在旧位置。

如何让它在打开时自动更新位置

最佳答案

您可以使用此处描述的技巧:http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/27950e73-0007-4e0b-9f00-568d2db1d979

我创建了一个 Blend behavior这使得它很容易与任何弹出窗口一起使用:

/// <summary>
/// A behavior that forces the associated popup to update its position when the <see cref="Popup.PlacementTarget"/>
/// location has changed.
/// </summary>
public class AutoRepositionPopupBehavior : Behavior<Popup> {
    public Point StartPoint = new Point(0, 0);
    public Point EndPoint = new Point(0, 0);

    protected override void OnAttached() {
        base.OnAttached();

        if (AssociatedObject.PlacementTarget != null) {
            AssociatedObject.PlacementTarget.LayoutUpdated += OnPopupTargetLayoutUpdated;
        }
    }

    void OnPopupTargetLayoutUpdated(object sender, EventArgs e) {
        if (AssociatedObject.IsOpen) {
            ResetPopUp();
        }
    }

    public void ResetPopUp() {
        // The following trick that forces the popup to change it's position was taken from here:
        // http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/27950e73-0007-4e0b-9f00-568d2db1d979
        Random random = new Random();
        AssociatedObject.PlacementRectangle = new Rect(new Point(random.NextDouble() / 1000, 0), new Size(75, 25));
    }
}

这是一个如何应用该行为的示例:

<Popup ...>
    <i:Interaction.Behaviors>
        <Behaviors:AutoRepositionPopupBehavior />
    </i:Interaction.Behaviors>
</Popup>

关于c# - 如何使 WPF Combobox 的下拉列表保持打开和放置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5339301/

相关文章:

c# - Asp.Net 中的空对象引用

c# - ListView 未更新项目源 ObservableCollection 项目属性更改

c# - WPF - 从 DataTemplate 创建 UI 对象

c# - 我可以在 Python3 中使用不同的代码点吗?

c# - Silverlight DataGrid 列验证

.net - Visual Studio 2008 构建依赖链

c# - 从 Print Spooler API 获取打印作业的用户域名

.net - WPF 将集合绑定(bind)到 ComboBox 并选择一个项目

c# - AWS 日志记录不工作

c# - 如何在运行时引用 DLL?