Tuesday, December 2, 2014

BooleanToVisibilityConverter - alternative way

Quite a departure from the regular use of the visibility converter

Reference- http://architects.dzone.com/articles/goodbye?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+zones%2Fdotnet+%28.NET+Zone%29

Old Method
Visibility={Binding IsVisible,Converter={StaticResource BooleanToVisibilityConverter}}

New Method

Usage
<TextBlock Text="I am visible!"
                       Style="{StaticResource PhoneTextExtraLargeStyle}"
                       attachedProperties:Alt.IsVisible="{Binding IsVisible}"
                       />
Attached Property - Class

public static partial class Alt
    {
        public static readonly DependencyProperty IsVisibleProperty = DependencyProperty.RegisterAttached(
            "IsVisible"typeof(bool?), typeof(Alt), new PropertyMetadata(default(bool?), IsVisibleChangedCallback));

        private static void IsVisibleChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var fe = d as FrameworkElement;
            if (fe == null)
                return;

            fe.Visibility = ((bool?)e.NewValue) == true
                ? Visibility.Visible
                : Visibility.Collapsed;
        }

        public static void SetIsVisible(DependencyObject element, bool? value)
        {
            element.SetValue(IsVisibleProperty, value);
        }

        public static bool? GetIsVisible(DependencyObject element)
        {
            return (bool?)element.GetValue(IsVisibleProperty);
        }
    }

No comments:

Post a Comment