Design-time-only background color in WPF?

前端 未结 5 957
伪装坚强ぢ
伪装坚强ぢ 2020-12-13 03:53

In WPF XAML there is the convenient DesignHeight and DesignWidth, for instance in code as



        
5条回答
  •  别那么骄傲
    2020-12-13 04:40

    This is the complete solution for DesignBackground:

    public class DesignTimeProperties : DependencyObject
        {
            private static readonly Type OwnerType = typeof(DesignTimeProperties);
    
            #region DesignBackground (attached property)
    
            public static Brush GetDesignBackground(DependencyObject obj)
            {
                return (Brush)obj.GetValue(DesignBackgroundProperty);
            }
    
            public static void SetDesignBackground(DependencyObject obj, Brush value)
            {
                obj.SetValue(DesignBackgroundProperty, value);
            }
    
            public static readonly DependencyProperty DesignBackgroundProperty =
                DependencyProperty.RegisterAttached(
                    "DesignBackground",
                    typeof (Brush),
                    OwnerType,
                    new FrameworkPropertyMetadata(Brushes.Transparent,
                        DesignBackgroundChangedCallback));
    
            public static void DesignBackgroundChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                if (IsInDesignMode)
                {
                    var control = d as Control;
                    var brush = e.NewValue as Brush;
                    if (control != null && brush != null)
                    {
                        control.Background = brush;
                    }
                }
            }
    
            public static bool IsInDesignMode
            {
                get
                {
                    return
                        ((bool)
                            DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof (DependencyObject)).DefaultValue);
                }
            }
    
            #endregion
    
        }
    

    Usage:

    
    

提交回复
热议问题