2012-04-08 96 views
1

我有一個按鈕樣式。該樣式包含Button的ControlTemplate。 ControlTemplate包含名稱爲「ImgButton」的圖像。如何在WPF派生樣式中重寫基礎樣式控件模板?

我想使這種風格作爲其他按鈕的基礎風格,並且想要覆蓋不同按鈕的圖像控件的「源」屬性。

任何想法?

回答

3

您可以創建將提供屬性以分配源的附加行爲。您應該使用TemplatedParent作爲RelativeSource將圖像綁定到模板中的此屬性。在派生樣式中,您可以簡單地使用Setter(s)來指定不同的Source。

附behavoir:

public static class ImageSourceBehavior 
{ 
    public static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached(
     "Source", typeof(ImageSource), typeof(ImageSourceBehavior), 
     new FrameworkPropertyMetadata(null)); 

    public static ImageSource GetSource(DependencyObject dependencyObject) 
    { 
     return (ImageSource)dependencyObject.GetValue(SourceProperty); 
    } 

    public static void SetSource(DependencyObject dependencyObject, ImageSource value) 
    { 
     dependencyObject.SetValue(SourceProperty, value); 
    } 
} 

樣式:

<Style x:Key="Style1" 
     TargetType="Button"> 
    <Setter Property="local:ImageSourceBehavior.Source" 
      Value="..."/> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="Button"> 
       <Image Source="{Binding Path=(local:ImageSourceBehavior.Source),RelativeSource={RelativeSource TemplatedParent}}"/> 
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

<Style x:Key="Style2" 
     BasedOn="{StaticResource Style1}" 
     TargetType="Button"> 
    <Setter Property="local:ImageSourceBehavior.Source" 
      Value="..."/> 
</Style> 
+1

+1,這是我使用過的方法。幾個月前我寫了一篇博客文章:http://tomlev2.wordpress.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/ – 2012-04-08 09:11:37

+0

謝謝,很好的解決方案。 – Syed 2012-04-09 05:38:20