Tuesday, January 08, 2013

Visibility Hidden Behavior for WinRT

In my last post, I lamented the loss of the Hidden in the Windows.UI.Xaml.Visibility enumeration. Here’s an ultra-simple attached property that simulates Hidden by changing the opacity and hit testability of the element:

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
using Windows.UI.Xaml;
 
namespace Blog.VisibilityHiddenDemo
{
    public class VisibilityHiddenBehavior : DependencyObject
    {
        public static readonly DependencyProperty IsVisibleProperty =
            DependencyProperty.RegisterAttached("IsVisible", typeof(bool), typeof(VisibilityHiddenBehavior),
                new PropertyMetadata(true, OnIsVisibleChanged));
 
        public static bool GetIsVisible(DependencyObject obj)
        {
            return (bool)obj.GetValue(IsVisibleProperty);
        }
 
        public static void SetIsVisible(DependencyObject obj, bool value)
        {
            obj.SetValue(IsVisibleProperty, value);
        }
 
        private static void OnIsVisibleChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var element = d as FrameworkElement;
            if (element != null)
            {
                var visible = (bool)e.NewValue;
                element.Opacity = visible ? 1 : 0;
                element.IsHitTestVisible = visible;
            }
        }       
    }
}

Free as in beer.

Happy coding.

0 comments: