Friday, March 4, 2011

How do I determine at runtime whether the style applied to an object is the default style?

I want to be able to apply a style at runtime to an object ONLY if the current style is the default style. I don't want to override any user defined styles. Anyone know how to do this?

From stackoverflow
  • Check the DefaultStyleKeyProperty, which is a static property of any custom control.

    string styleKeyName = DefaultStyleKeyProperty.Name;
    

    Usually if there is no style associated with the control, the Name will be "DefaultStyleKey"

  • It appears you can do it this way:

    DependencyPropertyHelper.GetValueSource(
        someControl, FrameworkElement.StyleProperty).BaseValueSource 
        == BaseValueSource.Default;
    

    You can wrap that up in an extension method like this:

    static public bool HasDefaultStyle(this FrameworkElement item)
    {
        return DependencyPropertyHelper.GetValueSource(
            item, FrameworkElement.StyleProperty).BaseValueSource 
            == BaseValueSource.Default;
    }
    

    Then you can just call someControl.HasDefaultStyle().

    Also, have a look at this article: Default Templates in WPF

    Micah : Bonus points for the extension method idea!!

0 comments:

Post a Comment