我试图将焦点带到网格元素上,当我用鼠标悬停在XAML文件的基础上。我有以下代码,目前尚未设置焦点。
<Grid x:Class="MyApp.MyClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
d:DataContext="{Binding Source={d:DesignInstance Type=trackPlot:MyViewModel}}"
Focusable="True"
Name="MainGrid">
<Grid.Style>
<Style TargetType="{x:Type Grid}">
<Style.Triggers>
<Trigger Property="IsFocused" Value="False">
<Setter Property="Background" Value="Transparent"/>
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Green"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=MainGrid}"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Style>
....Grid Contents here....
</Grid>
前两个触发器就在那里,可以很明显地表明,如果我在网格上,网格已经专注于并工作。第三个触发器是我试图设置焦点并且无法正常工作的地方。
在您的情况下,我建议您使用reactracteRce.self在焦点绑定中:
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}"/>
</Trigger>
我认为原因是绑定的表达式搜索元素名称不带检查目标元素名称本身。
我还可以提供我的完整示例。
如果我正确理解,我认为您想要类似的东西:
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="IsFocused" Value="True" />
</Trigger>
这个问题的答案是添加一个附加的网格层并在其中触发。我不知道为什么您不能使用文件的基本元素,但似乎不起作用。
<Grid x:Class="MyApp.MyClass"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
d:DataContext="{Binding Source={d:DesignInstance Type=trackPlot:MyViewModel}}">
<Grid Focusable="True" Name="MainGrid">
<Grid.Style>
<Style TargetType="{x:Type Grid}">
<Style.Triggers>
<Trigger Property="IsFocused" Value="False">
<Setter Property="Background" Value="Transparent"/>
</Trigger>
<Trigger Property="IsFocused" Value="True">
<Setter Property="Background" Value="Green"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="FocusManager.FocusedElement" Value="{Binding ElementName=MainGrid}"/>
</Trigger>
</Style.Triggers>
</Style>
</Grid.Style>
....Grid Contents here....
</Grid>
</Grid>