Tono Nam
Tono Nam

Reputation: 36048

Apply style to multiple controls when a style trigger fires in xaml

When the user enters info I want all the controls to look and act the same way, as a result I have done the following.

The label and textbox controls are in a stackpanel as:

    <StackPanel Style="{StaticResource ResourceKey=myInput}" HorizontalAlignment="Left">
        <Label Content="Label" Name="label1"  />
        <TextBox Name="textBox1"  ></TextBox>
    </StackPanel>

the style "myInput" is:

<Style x:Key="myInput" TargetType="{x:Type StackPanel}">
    <Style.Resources>
            <Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type Label}}">
                <Setter Property="FontSize" Value="12" />
            </Style>
            <Style TargetType="{x:Type TextBox}">
                <Setter Property="Margin" Value="5,-5,2,2"></Setter>
                <Setter Property="Height" Value="23"/>
                <Setter Property="VerticalAlignment" Value="Top"/>
                <Style.Triggers>
                    <Trigger Property="IsFocused" Value="true">
                        <Setter Property="Background" Value="Blue" >                                
                        </Setter>                           
                    </Trigger>
                </Style.Triggers>
            </Style>
    </Style.Resources>
</Style>

Now every time that I apply that style to a stackpanel that has a label and a textbox the background of the textbox changes to blue when it receives focus.

How could I set the label's fontweight to bold also when that event fires? I will like to do this with xaml.

Upvotes: 1

Views: 1934

Answers (1)

Rachel
Rachel

Reputation: 132548

Use a DataTrigger on your Label which looks to see if the keyboard focus is inside of the parent StackPanel that contains both objects

<Style TargetType="{x:Type Label}" BasedOn="{StaticResource {x:Type Label}}">
    <Setter Property="FontSize" Value="12" />
    <Style.Triggers>
        <DataTrigger Value="True" Binding="{Binding IsKeyboardFocusWithin,
            RelativeSource={RelativeSource AncestorType={x:Type StackPanel}}}">
            <Setter Property="FontWeight" Value="Bold" />
        </Trigger>
    </Style.Triggers>
</Style>

Upvotes: 2

Related Questions