2012-04-08 4 views
1

버튼 스타일이 있습니다. 이 스타일에는 Button 용 ControlTemplate이 포함되어 있습니다. ControlTemplate에는 이름이 "ImgButton"인 이미지가 포함되어 있습니다.WPF에서 파생 스타일의 기본 스타일 컨트롤 템플릿을 재정의하는 방법은 무엇입니까?

다른 버튼의 기본 스타일로이 스타일을 만들고 싶고 다른 버튼의 이미지 컨트롤의 "소스"속성을 무시하고 싶습니다.

아이디어가 있으십니까?

답변

3

소스를 할당하는 속성을 제공하는 연결된 동작을 만들 수 있습니다. RelativeSource로 TemplatedParent를 사용하여 템플릿의이 속성에 이미지를 바인딩해야합니다. 파생 된 스타일에서는 Setter를 사용하여 다른 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

일이 내가 너무 사용하는 방법입니다. 몇 달 전에 블로그 게시물을 썼습니다. http://tomlev2.wordpress.com/2011/10/01/wpf-creating-parameterized-styles-with-attached-properties/ –

+0

감사합니다. 멋진 솔루션입니다. – Syed

관련 문제