如何在WPF中禁用所有自定义样式

时间:2016-10-17 07:02:24

标签: c# wpf xaml

我覆盖了代码中某些控件的默认样式。在此之后,我想禁用所有控件的所有子项(深度递归)的所有自定义样式。例如xaml:

    <StackPanel>
        <StackPanel.Resources>
            <Style  TargetType="Button">
                <Setter Property="Background" Value="Red"/>
            </Style>
            <Style TargetType="TextBlock">
                <Setter Property="Background" Value="Red"/>
            </Style>
        </StackPanel.Resources>
        <Button>red style here is ok</Button>
        <TextBlock> also ok</TextBlock>
        <StackPanel>
            <StackPanel.Resources>
                <!-- magic command to disable ALL custom styles, for all controls like 
                <Style TargetType = "FrameworkElement"/>   -->
            </StackPanel.Resources>
            <Button> no style plz </Button>
            <TextBlock> bad style-_- </TextBlock>
        </StackPanel>
    </StackPanel>

我知道我可以使用style = null,但它对我来说是不好的解决方案,因为我需要为每种类型的控件应用这个技巧。我怎样才能解决我的问题?

1 个答案:

答案 0 :(得分:2)

您可以注入一个空白样式,该样式优先于您的其他样式。像:

<StackPanel>
    <StackPanel.Resources>
        <Style  TargetType="Button">
            <Setter Property="Background" Value="Red"/>
        </Style>
        <Style TargetType="TextBlock">
            <Setter Property="Background" Value="Red"/>
        </Style>
    </StackPanel.Resources>
    <Button>red style here is ok</Button>
    <TextBlock> also ok</TextBlock>
    <StackPanel>
        <StackPanel.Resources>
            <!-- magic command to disable ALL custom styles, for all controls -->
            <Style  TargetType="Button" />
            <Style TargetType="TextBlock" />
        </StackPanel.Resources>
        <Button> no style plz </Button>
        <TextBlock> bad style-_- </TextBlock>
    </StackPanel>
</StackPanel>