views:

46

answers:

1

If I have a set of controls within a StackPanel, is there a generic way to change the background of the stackpanel when any control within the StackPanel gains focus? (and obviously switch the background back when no control in the StackPanel has focus). The following code works for me, but it would be nice to have a generic way to accomplish this task versus having to list each control in every StackPanel in my page.

Thanks!

<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> 
+2  A: 

Yes. You can do that. Just use IsKeyboardFocusWithin property for the trigger, like this:

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

Do remember though, that you need to tell the trigger to look for the property in the same element, hence, RelativeSource={RelativeSource Self}. Alternatively, you can name the stack panel and use this xaml too:

<StackPanel Margin="5" x:Name="stackPanel">
    ...
                <DataTrigger Binding="{Binding ElementName=stackPanel, Path=IsKeyboardFocusWithin}" Value="True">
    ...
Yogesh
Cool! Exactly what I was looking for! Thanks so much!
Todd Fisher