2009-04-16 67 views
0

我想對所有的Image s和AutoGreyableImage s(我的自定義控件繼承自Image)使用相同的樣式。我在應用範圍內聲明以下樣式:如何在WPF中繼承基於類型的樣式?

<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> 

但是AutoGreyableImage s不接受樣式。這也不起作用:

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

這樣做的正確方法是什麼?

回答

3

你必須使用在從屬風格StaticResource的參考。

試試這個:

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

它適用於我。

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>