Ramblings of a .NET Developer

14 December 2013

Saturday, December 14, 2013 | by Paul | Categories: , , | No comments
So the projects I work on are usually quite large, often hitting over 1m lines of code. And, sometimes it is nice to add some buttons into the application which are there just for development purposes.

As one of my developers was hacking a way of doing this by leaving this out of his commits, it seemed like an opportunity to add something to reduce this management effort and eliminate errors when committing and pushing code in mecurial.

So, below is a simple attached property that will only render the control when the app is a DEBUG build.

    public static class Runtime
    {
        public static bool GetDebugOnly(DependencyObject obj)
        {
            return (bool)obj.GetValue(DebugOnlyProperty);
        }

        public static void SetDebugOnly(DependencyObject obj, bool value)
        {
            obj.SetValue(DebugOnlyProperty, value);
        }

        // Using a DependencyProperty as the backing store for DebugOnly.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty DebugOnlyProperty =
            DependencyProperty.RegisterAttached("DebugOnly", typeof(bool), typeof(Runtime), new UIPropertyMetadata(false, OnDebugOnlyChanged));

        private static void OnDebugOnlyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            var ui = sender as UIElement;
            if (ui != null)
            {
                if ((bool)e.NewValue)
                {
#if !DEBUG
                ui.Visibility = Visibility.Collapsed;
                ui.IsEnabled = false;
#endif
                }
            }
        }
    }

Now just just use the attached property where you need to.


0 comments:

Post a Comment