在 XAML 中调整控件的当前样式

Adjusting the current Style of a Control in XAML

假设我们有一个 ListView。在我们的 Resources 中的某个地方,有一个 Style 用于 ListView,它会被自动应用。 Style 设置 ItemContainerStyle:

<Window.Resources>
    <Style TargetType="{x:Type ListView}">
        <Setter Property="ItemContainerStyle">
            ...
        </Setter>
    </Style>
</Window.Resources>
...
<ListView x:Name="SpecialListView">
    ...
</ListView>

现在我想更改 SpecialListViewItemContainerStyle。但是我不想完全取代它。相反,我只想设置一个 属性(比方说 Background)。

我能想出的唯一解决方案是在 Resources 中命名用于 ItemContainerStyleStyle 并基于它创建一个新的。不过,我不想那样做。我们可能不知道应用了哪个 Style 或者可能无法设置子 Style.

的名称

可能吗?

好的,这可能有点简化。但显示了主要思想

<Window.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="Foreground" Value="Green"></Setter>
            <Setter Property="Background" Value="Red"></Setter>
        </Style>
    </Window.Resources>
    <StackPanel>
        <TextBox>
            <TextBox.Style>
                <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
                    <Setter Property="Background" Value="Yellow"></Setter>
                </Style>
            </TextBox.Style>
            Tb1
        </TextBox>
        <TextBox>Tb2</TextBox>
        <TextBox>Tb3</TextBox>
    </StackPanel>

如果你能区分具体情况,你可以使用转换器。

在特定 属性 绑定到特定转换器的通用样式中。 转换器的默认逻辑 returns 通用样式值,在特定情况下为其他值。