0

我用 x:Key 引用的资源字典中有一个外部样式资源。它有一个 x:TargetType 指定一个目标(TextBlock)。是否可以将此应用于包含 TextBlock 的控件,并使该控件中的所有 TextBlock 元素都应用样式?

谢谢,罗伯特

4

4 回答 4

4

最简单的方法是在控件中定义一个基于外部样式资源的样式,但不要指定 x:Key,只指定 TargetType。

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

如果没有键,它将应用到控件中的所有 TextBlocks。

于 2009-08-11T21:12:45.700 回答
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>
于 2009-08-12T11:37:56.573 回答
0

不,但您可以自动将样式应用于某种类型的所有元素,如下所示:

<!-- Applies to all buttons in scope of this style -->
<Style x:Key="{x:Type Button}" TargetType="{x:Type Button}">
   ...
</Style>
于 2009-08-11T21:12:28.587 回答
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>

自定义控件“test”中的文本块现在显示为蓝色前景。

于 2009-08-11T21:55:38.170 回答