Friday, April 29, 2011

How to inherit type-based styles in WPF?

I want to use the same style for all Images and AutoGreyableImages (my custom control that inherits from Image). I have the following style declared application-wide:

<Style TargetType="{x:Type Image}"
    x:Key="ImageType">
    <Setter Property="Stretch"
            Value="Uniform" />
    <Setter Property="Height"
            Value="16" />
    <Setter Property="Width"
            Value="16" />
    <Setter Property="SnapsToDevicePixels"
            Value="True" />
</Style>

But the AutoGreyableImages don't accept the style. This doesn't work either:

<Style TargetType="{x:Type my:AutoGreyableImage}"
       BasedOn="{DynamicResource ImageType}" />

What is the correct way to do this?

From stackoverflow
  • It works fine for me.

    AutoGreyableImage.cs:

    public class AutoGreyableImage : Image
    {
        public static readonly DependencyProperty CustomProperty = DependencyProperty.Register("Custom",
         typeof(string),
         typeof(AutoGreyableImage));
    
        public string Custom
        {
         get { return GetValue(CustomProperty) as string; }
         set { SetValue(CustomProperty, value); }
        }
    }
    

    Window.xaml:

    <Window.Resources>
     <Style TargetType="Image" x:Key="ImageStyle">
      <Setter Property="Stretch" Value="Uniform"/>
     </Style>
    
     <Style TargetType="{x:Type local:AutoGreyableImage}" BasedOn="{StaticResource ImageStyle}">
      <Setter Property="Custom" Value="Hello"/>
      <Setter Property="Width" Value="30"/>
     </Style>
    </Window.Resources>
    <Grid>
     <local:AutoGreyableImage Source="C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures\Winter.jpg"/>
    </Grid>
    

    HTH, Kent

  • You have to use a StaticResource reference in the dependent style.

    Try this:

    <Style TargetType="{x:Type my:AutoGreyableImage}" 
           BasedOn="{StaticResource ImageType}" />
    

0 comments:

Post a Comment