2014-11-21 66 views
0

我想對兩個控件使用相同樣式的,只需更改其層次結構中較深的兩種背景色。從模板中根據父項更改屬性

我有一個TextBox,其ScrollViewer,風格樣式併爲其ScrollBarBackground作爲邊框模板,其ThumbBackground作爲邊框的樣式。和我一起。

如何使用僅TextBox更改兩個背景(編程或不)?

......... .......... ..........

<!-- ScrollBar Style --> 
    <Style x:Key="{x:Type ScrollBar}" TargetType="ScrollBar"> 
     .... 
     <Style.Triggers> 
      <Trigger Property="Orientation" Value="Horizontal"> 
       .... 
       <Setter Property="Template" Value="{StaticResource HorizontalScrollBarTemplate}"/> 
       .... 
      </Trigger> 
     </Style.Triggers> 
    </Style> 

<!-- Horizontal Scrollbar Template --> 
    <ControlTemplate x:Key="HorizontalScrollBarTemplate" TargetType="{x:Type ScrollBar}"> 
     <Grid Background="{StaticResource ScrollBackroundBrush}"> 
      <Track Name="PART_Track"> 
       <Track.Thumb> 
        <Thumb Style="{StaticResource ScrollBarThumb}"/> 
       </Track.Thumb> 
      </Track> 
     </Grid> 
    </ControlTemplate> 

<!-- Thumb Style --> 
    <Style x:Key="ScrollBarThumb" TargetType="{x:Type Thumb}"> 
.... 
     <Setter Property="Template"> 
      .... 
        <Border 
         .... 
         Background="{StaticResource ScrollThumbBrush}"/> 
      .... 
     </Setter> 
    </Style> 

有一種方法來改變兩個背景(使用這個顏色和另一個相同的scrollviewer控件可能與另一個顏色)沒有改寫整個代碼?

例如有它的風格和寫:

TextBox tb1 = new TextBox(); 
tb1.Style = /*style*/ 
tb1.BackgroundOfScroll = /*brush11*/ 
tb1.BackgroundOfThumb = /*brush12*/ 


TextBox tb2 = new TextBox(); 
tb2.Style = /*style*/ 
tb2.BackgroundOfScroll = /*brush21*/ 
tb2.BackgroundOfThumb = /*brush22*/ 

回答

1

我做出了相應的例子。如果您只設置了一種顏色,則可以使用標記屬性,因爲它是DependencyProperty。然後創建兩個連接的性能,並獲得他們如下:

<Button local:Color.CustomBackground="CadetBlue"> 
      <Button.Template> 
       <ControlTemplate TargetType="Button"> 
        <ContentPresenter> 
         <ContentPresenter.ContentTemplate> 
          <ItemContainerTemplate> 
           <Border Width="50" Height="{Binding RelativeSource={RelativeSource Self}, Path=Width}" 
             Background="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=(local:Color.CustomBackground)}"> 

           </Border> 
          </ItemContainerTemplate> 
         </ContentPresenter.ContentTemplate> 
        </ContentPresenter> 
       </ControlTemplate> 
      </Button.Template> 
     </Button> 

C#

public class Color : DependencyObject 
    { 
     private static readonly DependencyProperty CustomBackgroundProperty = 
      DependencyProperty.RegisterAttached("CustomBackground", typeof(SolidColorBrush), typeof(Color), 
       new PropertyMetadata(null)); 

     public static void SetCustomBackground(DependencyObject obj, SolidColorBrush color) 
     { 
      obj.SetValue(CustomBackgroundProperty, color); 
     } 

     public static SolidColorBrush GetCustomBackground(DependencyObject obj) 
     { 
      return (SolidColorBrush)obj.GetValue(CustomBackgroundProperty); 
     } 
    }