Search code examples
c#wpfbindingstatic-membersxaml-designer

Disable binding to static property during design-time


I like to bind to static properties whenever I can (e.g. when notification is not needed or when model anyway implement INotifyPropertyChanged for other purposes), e.g.:

Visibility="{Binding IsAdministractor, Source={x:Static local:User.Current}, Converter={local:FalseToCollapsedConverter}}"

The problem is that such evaluation works at design-time too, making it hard to work with designer.

Normal bindings doesn't work in design-time and I can utilize FallbackValue to specify design-time only values (I have never yet used FallbackValue in run-time).

Is there an easy way to make binding to static properties invalid (disable them) during design-time?

I can temporarily rename property, e.g. IsAdministrator123, but this is tedious.


Solution

  • You can check if you're in design mode either in the Converter or in the static Current or in the IsAdministractor(typo here?) property and just return whatever state you'd like to see.

    EDIT:

    Here's some code for a MarkupExtension (untested)

    public class BindingWithDesignSupport : MarkupExtension
    {
        public BindingWithDesignSupport(){}
    
        public BindingWithDesignSupport(BindingBase binding)
        {
            Binding = binding;
        }
    
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return DesignerProperties.GetIsInDesignMode(new DependencyObject()) ? DesignTimeValue : Binding.ProvideValue(serviceProvider);
        }
    
        public BindingBase Binding { get; set; }
    
        public object DesignTimeValue { get; set; }
    }
    

    you should be able to use it like:

    Visibility="{BindingWithDesignSupport {Binding IsAdministractor, Source={x:Static local:User.Current}, Converter={local:FalseToCollapsedConverter}},DesignTimeValue=Visibility.Visible}"