Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make WPF Combobox's Dropdown stays open & Placement

I want to have the Combobox editable and with the dropdown stays open.

At the moment with these properties been set:

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

Whenever the user click on the input textbox or the focus is changed to other controls, the dorpdown closes. So I updated the template (the one included in WPF Theme: BureauBlue) to have the Popup IsOpen="true" in this particular case that makes the dropdown stays open, but now when user drag&move the window's position, the dropdown will not update its position automatically and stay in the old position.

How can I make it automatically update its position while it is open?

like image 935
Bolu Avatar asked Mar 17 '11 12:03

Bolu


1 Answers

You can use the trick described here: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/27950e73-0007-4e0b-9f00-568d2db1d979

I created a Blend behavior that makes it easy to use with any popup:

/// <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));
    }
}

Here is an example how to apply the behavior:

<Popup ...>
    <i:Interaction.Behaviors>
        <Behaviors:AutoRepositionPopupBehavior />
    </i:Interaction.Behaviors>
</Popup>
like image 152
Pavlo Glazkov Avatar answered Oct 03 '22 14:10

Pavlo Glazkov