-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDropDownButtonBehavior.cs
63 lines (58 loc) · 2.45 KB
/
DropDownButtonBehavior.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
using System;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
// Newer code should use Microsoft.Xaml.Behaviors
using Microsoft.Xaml.Behaviors;
// Older code uses System.Windows.Interactivity
//using System.Windows.Interactivity;
namespace DropDownButtonExample
{
public class DropDownButtonBehavior : Behavior<Button>
{
private long attachedCount;
private bool isContextMenuOpen;
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.AddHandler(Button.ClickEvent, new RoutedEventHandler(AssociatedObject_Click), true);
}
void AssociatedObject_Click(object sender, System.Windows.RoutedEventArgs e)
{
Button source = sender as Button;
if (source != null && source.ContextMenu != null)
{
// Only open the ContextMenu when it is not already open. If it is already open,
// when the button is pressed the ContextMenu will lose focus and automatically close.
if (!isContextMenuOpen)
{
source.ContextMenu.AddHandler(ContextMenu.ClosedEvent, new RoutedEventHandler(ContextMenu_Closed), true);
Interlocked.Increment(ref attachedCount);
// If there is a drop-down assigned to this button, then position and display it
source.ContextMenu.PlacementTarget = source;
source.ContextMenu.Placement = PlacementMode.Bottom;
source.ContextMenu.IsOpen = true;
isContextMenuOpen = true;
}
}
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.RemoveHandler(Button.ClickEvent, new RoutedEventHandler(AssociatedObject_Click));
}
void ContextMenu_Closed(object sender, RoutedEventArgs e)
{
isContextMenuOpen = false;
var contextMenu = sender as ContextMenu;
if (contextMenu != null)
{
contextMenu.RemoveHandler(ContextMenu.ClosedEvent, new RoutedEventHandler(ContextMenu_Closed));
Interlocked.Decrement(ref attachedCount);
}
}
}
}