kstanoev
12/15/2014 - 7:17 PM

Code-behind of an Expander control that works in Windows 8.1 and Windows Phone 8.1 apps.

Code-behind of an Expander control that works in Windows 8.1 and Windows Phone 8.1 apps.

[TemplateVisualState(Name = "Expanded", GroupName = "ExpandStateGroup")]
[TemplateVisualState(Name = "Collapsed", GroupName = "ExpandStateGroup")]
public class ExpanderControl : ContentControl
{
	public static readonly DependencyProperty HeaderProperty =
		DependencyProperty.Register("Header", typeof(object), typeof(ExpanderControl), new PropertyMetadata(null));

	public static readonly DependencyProperty IsExpandedProperty =
		DependencyProperty.Register("IsExpanded", typeof(bool), typeof(ExpanderControl), new PropertyMetadata(false, OnIsExpandedChanged));

	public object Header
	{
		get { return (object)GetValue(HeaderProperty); }
		set { SetValue(HeaderProperty, value); }
	}

	public bool IsExpanded
	{
		get { return (bool)GetValue(IsExpandedProperty); }
		set { SetValue(IsExpandedProperty, value); }
	}

	protected override void OnApplyTemplate()
	{
		base.OnApplyTemplate();
		this.ChangeVisualState();
	}

	private static void OnIsExpandedChanged(DependencyObject sender, DependencyPropertyChangedEventArgs arg)
	{
	   var expander = sender as ExpanderControl;
	   expander.ChangeVisualState();
	}

	private void ChangeVisualState()
	{
		if (this.IsExpanded)
		{
			VisualStateManager.GoToState(this, "Expanded", false);
		}
		else
		{
			VisualStateManager.GoToState(this, "Collapsed", false);
		}
	}
}