Julia Meshcheryakova
Julia Meshcheryakova

Reputation: 3262

How to make style to extend but not override other styles

On the current window I have a Grid with multiple controls (labels, textboxes, buttons). General styles are set in App.xaml. Extensions for each control are set in Grid resources. Each control visibility is determined by viewmodel property value. Not to bind each controls visibility to it (it uses custom converter and this will cause lots duplications) I wish to have "MyVisible1" style.

The problem is if I apply this style it overlaps other properties. What value should I use in "BasedOn"? Or what else can I do to implement it?

<Grid>
    <Grid.Resources>
        <Style TargetType="{x:Type Control}" x:Key="MyVisible1">
            <Setter Property="Visibility" Value="{Binding ...}" />
        </Style>

        <Style TargetType="Label" BasedOn="{StaticResource {x:Type Label}}">
            <Setter Property="HorizontalAlignment" Value="Right" />
        </Style>
        <Style TargetType="TextBox" BasedOn="{StaticResource {x:Type TextBox}}">
            <Setter Property="Width" Value="80" />
            <Setter Property="HorizontalAlignment" Value="Left" />
        </Style>
        <Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
            <Setter Property="Width" Value="45" />
            <Setter Property="HorizontalAlignment" Value="Right" />
        </Style>
    </Grid.Resources>

    <TextBox Grid.Column="0" Grid.Row="0" Style="{StaticResource MyVisible1}"/>
</Grid>

Upvotes: 1

Views: 417

Answers (1)

Sheridan
Sheridan

Reputation: 69959

The only way that I can imagine that you can do this is to define a local implicit Style for this:

<Style TargetType="{x:Type Control}">
    <Setter Property="Visibility" Value="{Binding ...}" />
</Style>

By not defining an x:Key, this Style will be implicitly applied to all controls that extend the Control class and by declaring it locally, it will only apply to those elements in the current focus scope. So defining it in a Grid.Resources section will implicitly apply it to all controls within that Grid. You are then free to apply whatever additional Styles that you want to these controls.

Upvotes: 1

Related Questions