Create properties that only apply on design time

后端 未结 2 1103
情书的邮戳
情书的邮戳 2020-12-19 05:21

I am using visual studio dark theme. As a result when designing my views I cannot see the font if its black. A fix will be to set the background of the view to white. But ou

2条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-19 06:02

    You can create a static class with an attached property for design mode:

    using System;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Media;
    
    namespace Helpers.Wpf
    {
        public static class DesignModeHelper
        {
            private static bool? inDesignMode;
    
            public static readonly DependencyProperty BackgroundProperty = DependencyProperty
                .RegisterAttached("Background", typeof (Brush), typeof (DesignModeHelper), new PropertyMetadata(BackgroundChanged));
    
            private static bool InDesignMode
            {
                get
                {
                    if (inDesignMode == null)
                    {
                        var prop = DesignerProperties.IsInDesignModeProperty;
    
                        inDesignMode = (bool) DependencyPropertyDescriptor
                            .FromProperty(prop, typeof (FrameworkElement))
                            .Metadata.DefaultValue;
    
                        if (!inDesignMode.GetValueOrDefault(false) && Process.GetCurrentProcess().ProcessName.StartsWith("devenv", StringComparison.Ordinal))
                            inDesignMode = true;
                    }
    
                    return inDesignMode.GetValueOrDefault(false);
                }
            }
    
            public static Brush GetBackground(DependencyObject dependencyObject)
            {
                return (Brush) dependencyObject.GetValue(BackgroundProperty);
            }
    
            public static void SetBackground(DependencyObject dependencyObject, Brush value)
            {
                dependencyObject.SetValue(BackgroundProperty, value);
            }
    
            private static void BackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
            {
                if (!InDesignMode)
                    return;
    
                d.SetValue(Control.BackgroundProperty, e.NewValue);
            }
        }
    }
    

    And you can use it like this:

    xmlns:wpf="clr-namespace:Helpers.Wpf;assembly=Helpers.Wpf"
    
    
        

    You can use this approach to implement other property for design mode.

提交回复
热议问题