我可以仅在特定布局中将WPF样式应用于元素吗?

Pro*_*ofK 2 wpf xaml wpf-style

我有这样的TextBlock风格:

<Style TargetType="TextBlock" x:Key="FormLabel">
    <Setter Property="Height" Value="20" />
    <Setter Property="Margin" Value="10" />
    <Setter Property="TextAlignment" Value="Right" />
    <Setter Property="VerticalAlignment" Value="Center" />
</Style>
Run Code Online (Sandbox Code Playgroud)

我以Grid基础形式使用它,例如:

<TextBlock Text="Code" Grid.Row="1" Grid.Column="0" Style="{StaticResource FormLabel}" />
Run Code Online (Sandbox Code Playgroud)

现在TextBlock,我不想在网格中的每个位置上都重复样式名称,而是希望有一个Grid类似的样式:

<Style TargetType="Grid" x:Key="FormGrid">
    <Setter Property="Width" Value="400" />
    ...
</Style>
Run Code Online (Sandbox Code Playgroud)

然后,如果可能的话,我想修改我的TextBlock样式,使其仅适用于Gridwith样式的子元素FormGrid

这可能吗?如果可以,我如何实现呢?

Yar*_*rik 5

通过使用另一种样式中的隐式样式作为资源,确实可以做到这一点。举个例子:

...
<Window.Resources>
    <Style x:Key="FormGrid" TargetType="Grid">
        <Style.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="Height" Value="20" />
                <Setter Property="Margin" Value="10" />
                <Setter Property="TextAlignment" Value="Right" />
                <Setter Property="VerticalAlignment" Value="Center" />
            </Style>
        </Style.Resources>
        <Setter Property="Width" Value="400" />
    </Style>
</Window.Resources>
<StackPanel>
    <Grid Style="{StaticResource FormGrid}">
        <TextBlock Text="This text block is styled with FormGrid TextBlock implicit style."/>
    </Grid>        
    <TextBlock Text="This text block uses the default style."/>
</StackPanel>
...
Run Code Online (Sandbox Code Playgroud)