Changing the background color of a WPF StackPanel when an item in a panel has focus

If I have a set of controls in a StackPanel, is there a general way to change the background of a stack panel when any control in a StackPanel gets focus? (and, obviously, switch the background if there is no focus in the StackPanel control panel). The following code works for me, but it would be nice to have a general way to accomplish this task compared to having to list each control in every StackPanel on my page.

Thank!

<StackPanel Margin="5">
    <StackPanel.Style>
    <Style TargetType="{x:Type StackPanel}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding IsFocused, ElementName=chkOccupiedByMortgagor}" Value="true">
                <Setter Property="Background" Value="Gray" />
                <Setter Property="Opacity" Value=".5" />
            </DataTrigger>
            <DataTrigger Binding="{Binding IsFocused, ElementName=chkOccupiedByNewOwner}" Value="true">
                <Setter Property="Background" Value="Gray" />
                <Setter Property="Opacity" Value=".5" />
            </DataTrigger>
        </Style.Triggers>
    </Style>
</StackPanel.Style>
<CheckBox Margin="2" x:Name="chkOccupiedByMortgagor">Mortgagor</CheckBox>
<CheckBox Margin="2" x:Name="chkOccupiedByNewOwner">New Owner</CheckBox>
<CheckBox Margin="2" x:Name="chkOccupiedByTenant">Tenant</CheckBox>
<CheckBox Margin="2" x:Name="chkOccupiedByUnknownOccupant">Unknown Occupant</CheckBox>
</StackPanel> 
+3
source share
1 answer

. . IsKeyboardFocusWithin , :

<StackPanel Margin="5">
    <StackPanel.Style>
        <Style TargetType="{x:Type StackPanel}">
            <Style.Triggers>
                    <DataTrigger Binding="{Binding RelativeSource={RelativeSource Self}, Path=IsKeyboardFocusWithin}" Value="True">
                    <Setter Property="Background" Value="Gray" />
                    <Setter Property="Opacity" Value=".5" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </StackPanel.Style>
    <CheckBox Margin="2">Mortgagor</CheckBox>
    <CheckBox Margin="2">New Owner</CheckBox>
    <CheckBox Margin="2">Tenant</CheckBox>
    <CheckBox Margin="2">Unknown Occupant</CheckBox>
</StackPanel>

, , , , RelativeSource={RelativeSource Self}. , xaml :

<StackPanel Margin="5" x:Name="stackPanel">
    ...
                <DataTrigger Binding="{Binding ElementName=stackPanel, Path=IsKeyboardFocusWithin}" Value="True">
    ...
+7

Source: https://habr.com/ru/post/1767032/


All Articles