vladeck's junkyard

designer wannabe

Button Popup Behavior

on November 21, 2010

Another behavior that I wrote for my project. The code is simple and there aren’t many things to configure, but it is a good starting point for a nice button popup (many other examples I’ve seen are coded as custom controls; the same can be accomplished using this behavior):

namespace Foo
{
    public class ButtonPopupBehavior : Behavior<Button>
    {
        private readonly Popup popup_;

        public static DependencyProperty PopupProperty =
            DependencyProperty.Register(
                "Popup",
                typeof(UIElement),
                typeof(ButtonPopupBehavior),
                null
            );

        public ButtonPopupBehavior()
        {
            popup_ = new Popup() { StaysOpen = false };
        }

        public UIElement Popup
        {
            get { return (UIElement)GetValue(PopupProperty); }
            set { SetValue(PopupProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            
            AssociatedObject.Click += OnClick;
            AssociatedObject.IsVisibleChanged += OnIsVisibleChanged;

            popup_.PlacementTarget = AssociatedObject;
            popup_.Child = Popup;
        }

        protected override void OnDetaching()
        {
            AssociatedObject.Click -= OnClick;
            AssociatedObject.IsVisibleChanged -= OnIsVisibleChanged;
            
            base.OnDetaching();
        }

        private void OnClick(object sender, RoutedEventArgs e)
        {
            popup_.IsOpen = true;
        }

        private void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            if (!(bool)e.NewValue)
                popup_.IsOpen = false;
        }
    }
}

Advertisement

2 Responses to “Button Popup Behavior”

  1. Helge Klein says:

    This looks very good, but could you please provide an example of how to use the behavior from XAML?

  2. vladeck says:

    It can be used something like this:

    <Button>
      <Interactivity:Interaction.Behaviors>
        <Behaviors:ButtonPopupBehavior>
          <Behaviors:ButtonPopupBehavior.Popup>
            <!-- put here any control/controls you like to be shown as pop-up -->
          </Behaviors:ButtonPopupBehavior.Popup>
        </Behaviors:ButtonPopupBehavior>
      </Interactivity:Interaction.Behaviors>
    </Button>
    

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.