Nick Carlson
Nick Carlson

Reputation: 243

Xaml: Using a child control trigger to change a parent control property

I'm attempting to modify a property of a parent control via a trigger on a child control. Specifically, I'm attempting to modify the opacity of a Border's DropShaddowEffect via the OnKeyboardFocus trigger of the Border's child TextBox.

However, the setter's TargetName gives an error that the name is not recognized.

Here is the XAML:

<Border x:Name="HeaderTextBoxBorder">
    <Border.Effect>
        <DropShadowEffect Opacity="20"/>                                    
    </Border.Effect>
    <TextBox x:Name="HeaderTextBox">
        <TextBox.Style>
            <Style
                TargetType="{x:Type TextBox}">
                <!-- Attmpting to change opacity on focus -->
                <Style.Triggers>
                    <Trigger
                        Property="IsKeyboardFocused"
                        Value="True">
                            <Setter
                                <!-- The error occurs here -->
                                TargetName="HeaderTextBoxBorder"
                                Property="Effect">
                                <Setter.Value>
                                    <DropShadowEffect Opacity="100"/>
                                </Setter.Value>
                            </Setter>
                    </Trigger>
                </Style.Triggers>   
            </Style>
        </TextBox.Style>
    </TextBox>
</Border>

Looking at the XAML, is there anything that pops out as incorrect?

Thank you for your time.

Upvotes: 2

Views: 3788

Answers (2)

Parisa
Parisa

Reputation: 206

I am quite late :) The IsKeyboardFocusWithin can be used to solve this. This property will get set to true for an element when any child of that element has keyboard focus.

<Window.Resources>
    <Style x:Key="HoneydewFocus" TargetType="Border">
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="true">
                <Setter Property="Background" Value="Honeydew"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</Window.Resources>

<StackPanel>
    <Border Margin="10"
            Style="{StaticResource HoneydewFocus}">
        <TextBox Width="200" Height="25" Margin="10"/>
    </Border >
</StackPanel>

Upvotes: 0

CodeNaked
CodeNaked

Reputation: 41393

The Style is a separate namescope, so you won't be able to access your Border via it's name like that.

You'd need to bind the Border.Effect property to the TextBox.IsKeyboardFocused element and switch the opacity that way, something like:

<Border.Effect>
    <DropShadowEffect Opacity="{Binding ElementName=HeaderTextBox, Path=IsKeyboardFocused, Converter={StaticResource local:CustomConverter}" />
</Border.Effect>

Where CusotmConverter implement IValueConverter and returns either 20 or 100, depending on the boolean value.

Upvotes: 3

Related Questions