我正在尝试使用以下代码在组合框获得键盘焦点时更改边框颜色:
<Style TargetType="{x:Type ComboBox}">
<Setter Property="Foreground" Value="{DynamicResource TextBrush}" />
<Setter Property="Background" Value="{DynamicResource WindowBrush}" />
<Setter Property="SnapsToDevicePixels" Value="true" />
<!--<Setter Property="Template" Value="{DynamicResource ComboBoxTemplate}" />-->
<Setter Property="IsEditable" Value="False"/>
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="BorderBrush" Value="{DynamicResource FocusedOnSolidBorderBrush}" />
<Setter Property="BorderThickness" Value="2" />
</Trigger>
</Style.Triggers>
</Style>
这很好用。 但是,如果我按如下方式使用控件模板,它将停止工作。边框颜色更改将不再显示。
<ControlTemplate x:Key="ComboBoxTemplate" TargetType="{x:Type ComboBox}">
<Grid x:Name="grid">
<ToggleButton Grid.Column="2" x:Name="ToggleButton" Focusable="False" IsChecked="{Binding Path=IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}" ClickMode="Press" />
<ContentPresenter HorizontalAlignment="Left" Margin="3,3,23,3" x:Name="ContentSite" Focusable="False" VerticalAlignment="Center" Content="{TemplateBinding SelectionBoxItem}" ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}" ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}" IsHitTestVisible="False" />
<Popup IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" x:Name="Popup" Focusable="False" AllowsTransparency="True" PopupAnimation="Slide">
<Grid MaxHeight="{TemplateBinding MaxDropDownHeight}" MinWidth="{TemplateBinding ActualWidth}" x:Name="DropDown" SnapsToDevicePixels="True">
<Border x:Name="DropDownBorder" Background="{DynamicResource ControlBackgroundBrush}" CornerRadius="3,3,3,3" />
<ScrollViewer Margin="4,6,4,6" Style="{DynamicResource NuclearScrollViewer}" SnapsToDevicePixels="True" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" CanContentScroll="True" Foreground="{DynamicResource {x:Static SystemColors.ActiveCaptionTextBrushKey}}">
<StackPanel IsItemsHost="True" KeyboardNavigation.DirectionalNavigation="Contained" />
</ScrollViewer>
</Grid>
</Popup>
</Grid>
<ControlTemplate.Triggers>
</ControlTemplate.Triggers>
</ControlTemplate>
模板中的某些内容会覆盖组合框样式中指定的触发器。 谁能告诉我控制模板的哪一部分需要改变?为什么?
谢谢,
答案 0 :(得分:0)
您的新ControlTemplate
没有定义边框,也没有绑定到BorderBrush
和BorderThickness
属性,因此很明显,当焦点发生变化时,您将看不到边框。
换句话说,您的触发器仍然有效,并按预期更改属性值,但没有绑定到新值的UI元素。您可以通过向控件模板添加边框并绑定到这些属性来轻松解决此问题。例如:
<ControlTemplate x:Key="ComboBoxTemplate" TargetType="{x:Type ComboBox}">
<Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}">
<Grid x:Name="grid">
<!-- ... -->
</Grid>
</Border>
</ControlTemplate>