GreyableTextBlock

November 27, 2008

WPF naturaly doesn’t have image class, which supports Disable state. Alex P solved this problem. Label class support disable state, but TextBlock don’t. Sometimes you need to use TextBlock, not Label. So, here a little class GreyableTextBlock which addresed to this issue:

    public class GreyableTextBlock: TextBlock
    {
        static GreyableTextBlock()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(GreyableTextBlock), new FrameworkPropertyMetadata(typeof(GreyableTextBlock)));
            GreyableTextBlock.IsEnabledProperty.OverrideMetadata(typeof(GreyableTextBlock), new FrameworkPropertyMetadata(new PropertyChangedCallback(OnIsEnabledChanged)));
        }

        private Brush ForegroundBrush;
        private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            GreyableTextBlock text = (GreyableTextBlock)d;
            if (e.Property.Name.Equals("IsEnabled"))
            {
                if ((e.NewValue as bool?) == false)
                {
                    text.ForegroundBrush = text.Foreground;
                    text.Foreground = Brushes.Gray;
                }
                else if ((e.NewValue as bool?) == true)
                {
                    text.Foreground = text.ForegroundBrush;
                }
            }
        }
    }