2012-05-19

Articles

PopupHandler

 

The PopupHandler helps you closing a popup control. It will be closed as soon the user clicks somewhere else, resize or move the window.

 

alt

 

Usage

<UserControl x:Class="DW.SharpTools.Demo.PopupHandlerControl"
			 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
			 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
			 xmlns:Local="clr-namespace:DW.SharpTools.Demo"
			 mc:Ignorable="d" 
			 d:DesignHeight="300" d:DesignWidth="300">
	<Grid HorizontalAlignment="Center" VerticalAlignment="Center">
		<Local:PopupDemoControl Header="Click Me">
			<TextBlock Text="I'm in the popup" />
		</Local:PopupDemoControl>
	</Grid>
</UserControl>
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
					xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
					xmlns:Local="clr-namespace:DW.SharpTools.Demo">

	<Style TargetType="{x:Type Local:PopupDemoControl}">
		<Setter Property="Template">
			<Setter.Value>
				<ControlTemplate TargetType="{x:Type Local:PopupDemoControl}">
					<Grid>
						<ToggleButton IsChecked="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}"
									  ClickMode="Press">
							<ContentPresenter ContentSource="Header" />
						</ToggleButton>
						<Popup IsOpen="{Binding IsDropDownOpen, RelativeSource={RelativeSource TemplatedParent}}"
							   StaysOpen="True"
							   AllowsTransparency="True">
							<Border BorderBrush="Brown" BorderThickness="1" CornerRadius="2">
								<ContentPresenter Margin="10" />
							</Border>
						</Popup>
					</Grid>
				</ControlTemplate>
			</Setter.Value>
		</Setter>
	</Style>
	
</ResourceDictionary>
using System.Windows;
using System.Windows.Controls;

namespace DW.SharpTools.Demo
{
	public class PopupDemoControl : HeaderedContentControl
	{
		static PopupDemoControl()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(PopupDemoControl), new FrameworkPropertyMetadata(typeof(PopupDemoControl)));
		}

		public bool IsDropDownOpen
		{
			get { return (bool)GetValue(IsDropDownOpenProperty); }
			set { SetValue(IsDropDownOpenProperty, value); }
		}

		public static readonly DependencyProperty IsDropDownOpenProperty =
			DependencyProperty.Register("IsDropDownOpen", typeof(bool), typeof(PopupDemoControl), new UIPropertyMetadata(false));

		public override void OnApplyTemplate()
		{
			new PopupHandler().AutoClose(this, () => ClosePopup());
			base.OnApplyTemplate();
		}

		private void ClosePopup()
		{
			if (IsDropDownOpen)
			{
				IsDropDownOpen = false;
				// Do something other
			}
		}
	}
}