开发者

Change WPF StackPanel background color when an element in the panel has focus

开发者 https://www.devze.com 2023-01-18 11:42 出处:网络
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 backgro

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> 


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">
    ...
0

精彩评论

暂无评论...
验证码 换一张
取 消