How can you tell at run time if a 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 custom styles. Does anyone know how to do this?

+1


source to share


2 answers


It looks like you can do it like this:

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

      

You can wrap it in an extension way 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, check out this article: Default Templates in WPF

+3


source


Check the DefaultStyleKeyProperty value, 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"

-1


source







All Articles