如果我在StackPanel中有一组控件,当StackPanel中的任何控件获得焦点时,是否有通用的方法来更改stackpanel的背景? (当StackPanel中的控件没有焦点时,显然会切换背景)。下面的代码对我有用,但是有一个通用的方法来完成这个任务,而不必在我的页面中的每个StackPanel中列出每个控件,这将是很好的。
谢谢!
<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>
答案 0 :(得分:7)
是。你可以做到这一点。只需使用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">
...