2009-08-11 50 views
0

我在x:Key引用的資源字典中有一個外部樣式資源。它有一個指定目標(TextBlock)的x:TargetType。是否有可能將此應用於包含TextBlock的控件,並使該控件中的所有TextBlock元素具有應用的樣式?WPF/XAML:使用不同的TargetType設置樣式?

感謝, 羅伯特

回答

4

這樣做是定義一個最簡單的方法控件中基於外部樣式資源的樣式,但不指定x:Key,只是指定TargetType。

<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource SomeOtherStyle}"> 

沒有密鑰,它將自身應用於控件中的所有TextBlock。

0

沒有,但你可以自動樣式應用於某種類型的所有元素,像這樣:

<!-- Applies to all buttons in scope of this style --> 
<Style x:Key="{x:Type Button}" TargetType="{x:Type Button}"> 
    ... 
</Style> 
0

我認爲這是你在找什麼:

您的自定義用戶控件 「測試」:

<UserControl x:Class="WpfApplication4.test" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    Height="300" Width="300"> 
    <Grid> 
     <TextBlock>test</TextBlock> 
    </Grid> 
</UserControl> 

您的樣式文件 「RES/Styles.xaml」

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> 
<Style TargetType="{x:Type TextBlock}"> 
    <Style.Setters> 
     <Setter Property="Foreground" Value="Blue" /> 
    </Style.Setters> 
</Style> 

您的主窗口或父母:

<Window x:Class="WpfApplication4.Window1" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:uc="clr-namespace:WpfApplication4" 
Title="Window1" Height="300" Width="300"> 
<Window.Resources> 
    <ResourceDictionary> 
     <ResourceDictionary.MergedDictionaries> 
      <ResourceDictionary Source="Res/Styles.xaml"/> 
     </ResourceDictionary.MergedDictionaries> 
    </ResourceDictionary> 
</Window.Resources> 

<Grid> 
    <uc:test></uc:test> 
</Grid> 

在自定義控制「測試」的正文塊現在顯示與藍色前景。

+0

是的;除了這在Silverlight中不起作用。但這很酷;我通過將財產包裹在另一個財產中來解決它。謝謝! – 2009-08-12 00:26:27

1

擴大一點在其他評論。當你使用的語法如Brandon所示:

<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource SomeOtherStyle}"> 

BasedOn =「」基本上就是一種風格的「繼承」。這種風格將以其基礎風格爲基礎。這使您能夠使用僅在此情況下適用的選項來擴充樣式,或根據需要重新定義樣式的範圍。

您的字典文件中的樣式爲鍵控樣式,只能顯式應用。通過Brandon顯示,通過「重新定義」您的風格,您現在可以通過忽略該鍵來重新定義範圍,從而使其適用於該風格範圍內的所有目標類型元素。所以如果你所有的TextBlocks都在一個Grid中,你可能會有這樣的東西:

<Grid.Resources> 
<Style TargetType="{x:Type TextBlock}" BasedOn="{StaticResource MyBaseStyle}">     
</Style> 
</Grid.Resources> 
相關問題