2011-07-20 23 views
0

我有一個網格控制,其中每行包含一個StackPanel另一個控制裏面,每一個StackPanel中包含一個或多個的TextBlocks(而這個問題不是核心,如果有一個更好的方式來實現自定義網格的文本塊 - 即「標題標籤:內容」的行,我會很感激一些技巧)應用樣式Silverlight控件僅當控制是與特定的風格

無論如何...我想有一個標題行,其中stackpanel有一個黑暗背景和文本塊有白色,粗體文本,然後每隔一行有黑色文本。請注意,只有第一行是用Style HeaderRow定義的。我用了「支持算法FMP」來定義,只有標題行中的TextBlocks應該大膽/白色,但我發現,這個影響在其他行中的所有的TextBlocks太(即不具有另一種風格的定義)。

我切實希望能夠做到

樣品XAML

樣式:

<Style x:Key="TitleLabel" TargetType="TextBlock"> 
        <Setter Property="FontFamily" Value="Verdana"/> 
        <Setter Property="Margin" Value="5 0 0 0"/> 
        <Setter Property="Width" Value="105"/> 
        <Setter Property="FontWeight" Value="Bold"/> 
       </Style> 
       <Style x:Key="AlternatingRow" TargetType="StackPanel"> 
        <Setter Property="Background" Value="#f0f1ff"/> 
       </Style> 
       <Style x:Key="HeaderRow" TargetType="StackPanel"> 
        <Setter Property="Background" Value="#666666"/> 
       </Style> 
       <Style TargetType="TextBlock" BasedOn="StaticResource HeaderRow" > 
        <Setter Property="Foreground" Value="White"/> 
        <Setter Property="FontWeight" Value="Bold"/> 
       </Style> 

XAML

<Grid> 
        <Grid.RowDefinitions> 
         <RowDefinition Height="auto"/> 
         <RowDefinition Height="auto"/> 
         <RowDefinition Height="auto"/> 
         <RowDefinition Height="auto"/> 
         <RowDefinition Height="auto"/> 
         <RowDefinition Height="auto"/> 
        </Grid.RowDefinitions> 
        <StackPanel Orientation="Horizontal" Grid.Row="0" Style="{StaticResource HeaderRow}"> 
         <TextBlock Text="Header Row" /> 
        </StackPanel> 
        <StackPanel Orientation="Horizontal" Grid.Row="1" Style="{StaticResource AlternatingRow}"> 
         <TextBlock Text="HeaderLabel:" Style="{StaticResource TitleLabel}" /> 
         <TextBlock Text="Content" /> 
        </StackPanel> 
        <StackPanel Orientation="Horizontal" Grid.Row="2"> 
         <TextBlock Text="HeaderLabel" Style="{StaticResource TitleLabel}" /> 
         <TextBlock Text="Content" /> 
        </StackPanel> 
        <StackPanel Orientation="Horizontal" Grid.Row="3" Style="{StaticResource AlternatingRow}"> 
         <TextBlock Text="HeaderLabel" Style="{StaticResource TitleLabel}" /> 
         <TextBlock Text="Content" /> 
        </StackPanel> 
        <StackPanel Orientation="Horizontal" Grid.Row="4"> 
         <TextBlock Text="HeaderLabel" Style="{StaticResource TitleLabel}" /> 
         <TextBlock Text="Content" /> 
        </StackPanel> 
       </Grid> 

回答

0

你沒有正確使用StyleBasedOn財產。它所做的只是表明一種風格「擴展」了另一種風格,即它複製了其所有設置值。 (請注意,你的榜樣也會失敗,因爲你想在風格立足於另一個其中TargetTypes不兼容),這並不表明,當嵌套在另一個元素的樣式應用。

不幸的是Silverlight不有您所需要的功能,你不能基於視覺樹內元素位置的風格。你將要的風格各TextBlock明確。

雖然,我沒有創建使用CSS樣式而回的機制:

http://www.scottlogic.co.uk/blog/colin/2009/03/using-css-selectors-for-styling-in-wpf/

這可以讓你創建一個基於父元素選擇。