【问题标题】:Styling for direct children直接孩子的造型
【发布时间】:2021-02-02 13:51:40
【问题描述】:

鉴于此示例 XAML:

<TabControl>
    <TabItem Header="Test">
        <Grid> <!-- outer grid that should receive the styles -->
            <Grid.RowDefinitions><!-- ... --></Grid.RowDefinitions>
            <Grid.ColumnDefinitions><!-- ... --></Grid.ColumnDefinitions>
            <Grid Grid.Row="1" Grid.Column="1">
                <!-- inner grid, should NOT receive the styles -->
            </Grid>
        </Grid>
    </TabItem>
</TabControl>

如何设置TabItem 的所有直接Grid 子级,而没有其他Grid 在层次结构中的更深层次?

这是我试过的(我把这个放在App.xml):

<Style TargetType="TabItem">
    <Style.Resources>
        <Style TargetType="Grid">
            <Setter Property="Margin" Value="10" />
        </Style>
    </Style.Resources>
</Style>

(我知道我可以使用Style={StaticResource ...} 分配某些样式,但我必须将它单独应用于所有Grid,这似乎有很多不必要的代码......)

【问题讨论】:

  • 其他样式语言(例如 CSS)具有这些类型的选择器,它们对于拥有干净有序的代码非常有帮助。
  • WPF 没有提供这样的功能,没有人会错过它。
  • @Clemens 给定一个应用程序有几十个表单,您希望所有表单都有统一的样式。正确的做法是什么?
  • 你已经知道了。如果默认样式不适合,请明确设置一个。除此之外,还有 DataTemplates 和 UserControls。
  • 看起来我们越来越接近实际答案了... :-)

标签: wpf xaml app.xaml


【解决方案1】:

我如何设置TabItem 的所有直接Grid 子级,而没有其他Grid 在层次结构中更深?

通过一种或另一种方式为所有外部Grid 元素显式设置Style 属性。

例如,您可以创建一个自定义 Grid 类型,并将 Style 应用于:

public class OuterGrid : Grid { }

XAML

<Style TargetType="local:OuterGrid">
    <Setter Property="Margin" Value="10" />
</Style>
...
<local:OuterGrid>
    <!-- outer grid that should receive the styles -->
    <Grid Grid.Row="1" Grid.Column="1">
        <!-- inner grid, should NOT receive the styles -->
        <TextBlock>inner</TextBlock>
    </Grid>
</local:OuterGrid>

或者指定自定义Grid的默认值而不使用Style

public class OuterGrid : Grid
{
    public OuterGrid()
    {
        Margin = new Thickness(10);
    }
}

恐怕XAML中没有CSS子选择器(&gt;)的概念。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-27
    • 2016-01-22
    • 1970-01-01
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 2014-07-05
    • 2018-02-15
    相关资源
    最近更新 更多