2013-08-18 22 views
1

大家好,這是一個令我發瘋幾天的問題。無法在wpf中覆蓋控制前景色的問題

簡單地說,只要我聲明任何從TextBlock控件派生出來的前景色,前景色在設計時被識別,但在運行時它總是默認爲黑色。

它就好像前景屬性在控件上被忽略。

因此,例如,一般情況下我希望以下呈現一個按鈕,白色的文字:

<Button x:Name="MyButton" Content="Hello World" Foreground="White" ... /> 

然而,這呈現一個按鈕和前景文本顏色爲黑色。它有效地忽略了Foreground setter屬性。

只有這樣,才能得到這個達到預期效果是繼DO:

<Button x:Name="MyButton" .... > 
    <TextBlock Text="Hello World" Foreground="White"/> 
</Button> 

這樣的作品和按鈕白字正確呈現。但我知道我不應該明確地定義像這樣的按鈕textblock。

與從文本塊派生的任何內容相同的行爲。

有沒有人知道爲什麼會發生這種情況?

更新: 我檢查了適用於TextBox的樣式的解決方案。我已經在TextBlock上定義了我自己的樣式,它是:

<Style x:Key="TextBlockText" TargetType="{x:Type TextBlock}"> 
    <Setter Property="Foreground" Value="#FF63798F"/> 
    <Setter Property="FontSize" Value="14"/> 
    <Setter Property="VerticalAlignment" Value="Bottom"/> 
    <Setter Property="HorizontalAlignment" Value="Stretch"/> 
</Style> 

正如您所看到的,它定義了前景的值。 但是當我從我的資源字典中刪除這種風格上面的問題仍然存在。

其他信息是,我正在使用MahApps.Metro庫和我想知道這是否導致問題。

有沒有人有任何其他想法?甚至考慮在哪裏進行調查?

+0

你確定嗎?這適用於我''Button Content =「Hello World」Foreground =「White」/>''' –

+2

您可能有一個TextBlock默認樣式,它將前景設置爲黑色,查看整個解決方案TargetType =「{x:Type TextBlock} – makc

+0

還檢查TargetType =「Button」或ButtonBase。風格確實存在問題。 – abhishek

回答

2

WPF中的每個控件都有一個與之相關的模板。我想不管怎麼樣,你的按鈕上定義的樣式不計算前景屬性。

例如,

<Style x:Key="DialogButtonStyle" TargetType="Button"> 
    <Setter Property="Template"> 
     <Setter.Value> 
      <ControlTemplate TargetType="{x:Type Button}"> 
       <Grid> 
        <Ellipse Fill="{TemplateBinding Background}" 
          Stroke="{TemplateBinding BorderBrush}"/> 
         <TextBlock Foreground={TemplateBinding Foreground}"> 
         <ContentPresenter HorizontalAlignment="Center" 
              VerticalAlignment="Center"/></TextBlock> 
       </Grid>    
      </ControlTemplate> 
     </Setter.Value> 
    </Setter> 
</Style> 

你可以使用樣式= {StaticResource的DialogBu​​ttonStyle}而且按鈕定義前景​​。在這裏看到我們在TextBlock的Foreground上使用了TemplateBinding,而不是在裏面定義顏色。

1

我建議保持您的TextBlock樣式,並在您的Button或其他控件中,在Template級別添加一個具有TextBlock樣式的新資源。它將位於該模板的域中,因此它不會影響其他文本塊,但會覆蓋主要TextBlock的樣式。

例如:

<ControlTemplate> 
    <Grid> 
    <Grid.Resources> 
      <!-- Put a new/duplicate TextBlock Style here with 
       the appropriate Foreground color, or TemplateBinding 
       and it will override it for this Grid's children --> 
    </Grid.Resources> 
    <TextBlock /> 
    </Grid> 
</ControlTemplate>