Search code examples
c#wpfxamllistviewwpf-style

Adjusting the current Style of a Control in XAML


Let's say we have a ListView. Somewhere in our Resources there is a Style for ListView's which is being applied automatically. That Style sets the ItemContainerStyle:

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

Now I want to change the ItemContainerStyle of SpecialListView. However I don't want to completely replace it. Instead I just want to set one property (let's say Background).

The only solution I can come up with is naming the Style used for ItemContainerStyle in Resources and create a new one based on it. I don't want to do that, though. We might not know which Style is applied or might not be able to set the name for the sub-Style.

Is it possible?


Solution

  • Okay, this may be a little simplified. But shows the main idea

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