我试图在占据相同空间的两个单独的列表框中显示形状。我已将背景设置为透明和 {x:Null} 但鼠标单击仍被最顶部的列表框捕获,因此我无法从底层列表框中选择任何形状。
这是一些重现问题的示例代码。
<Grid>
<!-- ListBox 1 -->
<ListBox Background="{x:Null}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="{x:Null}"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Background="Transparent">
<Ellipse Width="100" Height="100" Stroke="Blue" StrokeThickness="10"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
1
</ListBox>
<!-- ListBox 2 -->
<ListBox Background="{x:Null}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<Canvas Background="{x:Null}"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="Canvas.Left" Value="100"/>
<Setter Property="Canvas.Top" Value="100"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<Ellipse Width="100" Height="100" Stroke="Blue" StrokeThickness="10"/>
</DataTemplate>
</ListBox.ItemTemplate>
1
</ListBox>
</Grid>
这就是我现在解决这个问题的方法,但我对其他建议持开放态度:) 我在 Grid 上启用了命中测试,并为两个 ListBox 禁用了它。然后我在事件处理程序中进行了命中测试
<Grid MouseDown="Grid_MouseDown"
IsHitTestVisible="True"
Background="Transparent">
<!-- ListBox 1 -->
<ListBox Background="Transparent"
IsHitTestVisible="True"
..>
</ListBox>
<!-- ListBox 2 -->
<ListBox Background="Transparent"
IsHitTestVisible="True"
..>
</ListBox>
</Grid>
事件处理程序和命中测试
private void Grid_MouseDown(object sender, MouseButtonEventArgs e)
{
Grid grid = sender as Grid;
Point ptCurrent = e.GetPosition(grid);
VisualTreeHelper.HitTest(grid, null, new HitTestResultCallback(HitTestCallback), new PointHitTestParameters(ptCurrent));
}
public HitTestResultBehavior HitTestCallback(HitTestResult htrResult)
{
ListBoxItem listBoxItem = GetVisualParent<ListBoxItem>(htrResult.VisualHit);
if (listBoxItem != null)
{
listBoxItem.IsSelected = true;
return HitTestResultBehavior.Stop;
}
return HitTestResultBehavior.Continue;
}
public T GetVisualParent<T>(object child) where T : Visual
{
DependencyObject c = child as DependencyObject;
while ((c != null) && !(c is T))
{
c = VisualTreeHelper.GetParent(c);
}
return c as T;
}