【发布时间】:2017-07-27 17:37:18
【问题描述】:
我正在努力实现的目标
为简单起见,我有一个单元格网格,我尝试在每个单元格获得焦点时将 FocusVisualStyle 虚线矩形添加到每个单元格。但是,根据其设计,该样式仅在使用键盘导航到元素时才有效。我希望达到相同的效果,但让它与键盘焦点和鼠标焦点(单击单元格时)一起工作。
我的尝试
我研究过使用像 Border 这样的容器,但它没有虚线,尝试使用虚线矩形并将其定位在元素上,但结果不一致。我还尝试将触发器附加到单元格的IsFocused 属性,但这仅适用于键盘焦点。
当前代码
现在我已将事件设置到单元格(StackPanel),允许我在网格中进行自定义导航。我目前的“视觉风格”是将背景更改为适用于鼠标和键盘焦点的颜色。我希望将背景更改换成单元格周围的虚线矩形,但是我尝试的 XAML 不起作用,因为 FocusVisualStyle 仅适用于键盘焦点。
这是我尝试过的 XAML 和 C# 的简化版本
XAML
<!-- The "cell" I'm trying to acheive a dashed border around -->
<StackPanel x:Key="ContactCell"
Focusable="True"
GotFocus="StackPanel_GotFocus"
LostFocus="StackPanel_LostFocus"
PreviewMouseDown="Contact_Select"
Style="{DynamicResource ContactFocusStyle}">
<!-- other children in here -->
</StackPanel>
<Style x:Key="ContactFocusStyle" TargetType="StackPanel">
<Style.Triggers>
<Trigger Property="IsFocused" Value="True">
<Setter Property="FocusVisualStyle"
Value="{DynamicResource MyFocusVisualStyle}"/>
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="MyFocusVisualStyle">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Stroke="Black"
StrokeDashArray="2 3"
Fill="Transparent"
StrokeDashCap="Round"
RadiusX="3"
RadiusY="3"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
C#
private void Contact_Select(object send, MouseButtonEventArgs e)
{
StackPanel sender = (StackPanel)send;
sender.Focus();
}
private void StackPanel_GotFocus(object sender, RoutedEventArgs e)
{
StackPanel s = (StackPanel)sender;
s.Background = Brushes.Red;
}
private void StackPanel_LostFocus(object sender, RoutedEventArgs e)
{
StackPanel s = (StackPanel)sender;
s.Background = Brushes.Transparent;
}
【问题讨论】: