2010-09-16 13 views
3

如果非要定義以下樣式:應用樣式的TextBlocks一個ContentPresenter中在Silverlight

<UserControl.Resources> 
    <Style TargetType="TextBlock" x:Key="ProblemStyle"> 
     <Setter Property="FontSize" Value="40"/> 
     <Setter Property="FontWeight" Value="Bold"/> 
    </Style> 
</UserControl.Resources> 

然後,當我有一個綁定到一個字符串ContentPresenter數據,在WPF我可以得到它的樣式文本按照以下XAML的要求:

<ContentPresenter Content="{Binding Problem}"> 
    <ContentPresenter.Resources> 
     <Style TargetType="TextBlock" BasedOn="{StaticResource ProblemStyle}" /> 
    </ContentPresenter.Resources> 
</ContentPresenter> 

但是,在Silverlight中,這是行不通的。有沒有一種適用於兩者的方法?

+1

我不明白。爲什麼不只是有一個'TextBlock'綁定到字符串? – 2010-09-16 15:28:01

+0

這是再現問題的最小示例。很容易想象一個更復雜的例子,它不能被一個綁定的「Te​​xtBlock」所取代。 – 2010-09-16 18:14:08

+0

@Kent - 因爲「問題」不一定是一個字符串。我已經更新了我的ViewModel,以便「問題」本身是一個TextBlock – 2010-09-17 08:31:11

回答

-1

第一張: 確保在應用程序嘗試呈現ContentPresenter之前正在加載樣式「ProblemStyle」。在Silverlight中,樣式定義的順序有所不同,如果它尚未被加載,那麼它可能不會讀取任何內容。

好吧,我將在這裏運行一些假設,第一個是你正在使用ContentControl來顯示內容並且ContentPresenter位於此控件的內部。

但爲什麼不爲ContentControl創建樣式?

<Style x:key="ProblemStyle" TargetType="ContentControl"> 
    <Setter Property="FontSize" Value="40"/> 
    <Setter Property="FontWeight" Value="Bold"/> 
</Style> 

然後,您的ContentControl將Style設置爲「ProblemStyle」的StaticResource。

由於默認情況下ContentControl中的模板具有ContentPresenter - 或者你可以定義樣式中ContentPresenter模板,以及:

<Style x:key="ProblemStyle" TargetType="ContentControl"> 
    <Setter Property="FontSize" Value="40"/> 
    <Setter Property="FontWeight" Value="Bold"/> 
    <Setter Property="Template"> 
    <Setter.Value> 
     <ControlTemplate TargetType="ContentControl"> 
      <Border> 
      <ContentPresenter Content="{TemplateBinding Content}"/> 
      </Border> 
     </ControlTemplate> 
    </Setter.Value> 
    </Setter> 
</Style> 

模板有隻是作爲一個佔位符給的,其中一個想法它會/可能位於。

+1

無法在ContentControl樣式中設置TextBlock的某些屬性,例如。 TextWrapping – Ilya 2014-08-13 10:33:53

5

使用TextElement附加屬性。你將無法設置樣式,但大多數影響文本塊的屬性都在那裏。

<ContentPresenter x:Name="ContentPresenter" 
           ContentSource="Header" 
           HorizontalAlignment="Left" 
           TextElement.FontFamily="Segoe UI" 
           TextElement.FontSize="12" 
           TextElement.FontWeight="Bold" 
           TextElement.Foreground="White" 
           RecognizesAccessKey="True" /> 
相關問題