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

标签 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>

我以基于 Grid 的形式使用它,例如:
<TextBlock Text="Code" Grid.Row="1" Grid.Column="0" Style="{StaticResource FormLabel}" />

现在,我不想在网格中的每个 TextBlock 上重复样式名称,而是更喜欢例如有一个 Grid 风格,如:
<Style TargetType="Grid" x:Key="FormGrid">
    <Setter Property="Width" Value="400" />
    ...
</Style>

然后,如果可能的话,我想修改我的 TextBlock 样式,使其仅在该元素是 Grid 样式的 FormGrid 的子元素时才适用于该元素。

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

最佳答案

通过在另一种样式中使用隐式样式作为资源,这确实是可能的。拿这个例子:

...
<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>
...

关于wpf - 我可以将 WPF 样式仅应用于特定布局中的元素吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41942763/

相关文章:

.net - 渲染隐藏的 Canvas 而不显示它?

c# - 获取DataGrid宽度

wpf - TextBlock TextWrapping 不换行 #2

c# - 跳棋和可移动人物 WPF

c# - 用 MahApps.Metro 无边框窗口的菜单替换窗口标题

c# - 无法覆盖 WPF 中 app.xaml 的按钮样式

wpf - 使用 WPF 样式为所有控件和文本 block 设置边距

wpf - ControlTemplate TargetType 与模板化类型不匹配

c# - 数据绑定(bind)到以枚举为键的字典中的条目

c# - WPF 中 CheckBox 的自定义鼠标命中区域