2013-11-21 85 views
6

我重寫了wpf擴展器的模板。 頭具有ContentPresenter爲ContentPresenter中的所有元素設置樣式

<ContentPresenter x:Name="HeaderContent" 
        Grid.Column="1" 
        Margin="0,0,4,0" 
        HorizontalAlignment="Left" 
        VerticalAlignment="Center" 
        RecognizesAccessKey="True" 
        SnapsToDevicePixels="True" 
        > 
    <ContentPresenter.Resources> 
     <Style BasedOn="{StaticResource Expanderheader-Naming}" 
       TargetType="{x:Type TextBlock}" /> 
    </ContentPresenter.Resources> 
</ContentPresenter> 

在哪裏我試圖加我的風格里面的所有的TextBlocks。 我的風格的作品,如果我設置頁眉爲屬性:

<Expander Header="HelloWorld"> 

但事實並非如此,當我嘗試將其設置在其他的方式。

<Expander> 
    <Expander.Header> 
     <Grid x:Name="MyGrid"> 
      <TextBlock>Hello Man</TextBlock> 
     </Grid> 
    </Expander.Header> 
</Expander> 

如何爲ContentPresenter中的任何TextBlocks設置此樣式?

回答

10

你在wpf中遇到了典型的風格繼承問題。

控件在初始化時查找它的樣式。控件查找樣式的方法是在邏輯樹中向上移動,並詢問邏輯父項是否存在父類資源字典中存儲的適當樣式。

向你解釋你在你的例子中做錯了什麼讓我們這樣想。

在第一個例子中,頭文件正好存儲「HelloWorld」,後來當控件處於初始化狀態時,「HelloWorld」將被注入到ContentPresenter中。這種方法提供了「HelloWorld」,ContentPresenter是它的邏輯父項,因此樣式可以被正確應用,因爲可以找到樣式。

在第二個示例中,您將創建一個Grid並在該Grid內部有一個TextBlock。

在控制初始化階段,TextBlock的邏輯父項是Grid,而且Grid的邏輯父項是Expander本身。當爲TextBlock尋找樣式時,WPF會詢問TextBlock的邏輯父項,如果它在TextBlock的資源中有適當的樣式並且答案將是NO。 Grid.Resources中的TextBlock沒有適當的樣式,並且Expander.Resources中沒有適當的TextBlock樣式。

恰當的樣式應該在ContentPresenter中,就在這種情況下,ContentPresenter不是邏輯樹的一部分。

這就是你如何失去你的第二個例子的風格。

爲了解決這個問題,我建議你堅持第一個例子或改變樣式存儲到的地方。通常所有樣式都應該存儲在Window.Resources中。

EDIT 2 看看仔細這個例子:

<Window.Resources> 
    <Style x:Key="textBlockStyle" TargetType="TextBlock"> 
     <Setter Property="Background" Value="Blue"/> 
    </Style> 


    <Style TargetType="Button"> 
     <Setter Property="Template"> 
      <Setter.Value> 
       <ControlTemplate TargetType="Button"> 
        <ContentPresenter> 
         <ContentPresenter.Resources> 
          <Style TargetType="TextBlock" BasedOn="{StaticResource textBlockStyle}"/> 
         </ContentPresenter.Resources> 
        </ContentPresenter> 
       </ControlTemplate> 
      </Setter.Value> 
     </Setter> 
    </Style> 
</Window.Resources> 
<StackPanel> 
    <Button Content="Yay, it worked!" /> 
    <Button> 
     <Grid> 
      <TextBox Text="It doesn't work this way!"/> 
     </Grid> 
    </Button> 
    <Button> 
     <Grid> 
      <Grid.Resources> 
       <Style TargetType="TextBlock" BasedOn="{StaticResource textBlockStyle}"></Style> 
      </Grid.Resources> 
      <TextBlock Text="Yay it works again! Woop Woop"/> 
     </Grid> 
    </Button> 
</StackPanel> 
+0

不好意思可能是我不明白,而是這是否意味着如果我使用: <樣式的TargetType =「{X:類型Grid>}> user1706449

相關問題