我正在学习wpf中的路由事件,并尝试以下示例,
文件 - Window1.xaml
<ScrollViewer VerticalScrollBarVisibility="Auto">
<UniformGrid MouseDown="UniformGrid_MouseDown">
<Button x:Name="Button1">1</Button>
<Button x:Name="Button2">2</Button>
<Button x:Name="Button3">3</Button>
<Button x:Name="Button4">4</Button>
<Button x:Name="Button5">5</Button>
<Button x:Name="Button6">6</Button>
<Button x:Name="Button7">7</Button>
<Button x:Name="Button8">8</Button>
<Button x:Name="Button9">9</Button>
</UniformGrid>
</ScrollViewer>
文件 - Window1.xaml.cs
private void UniformGrid_MouseDown(object sender, MouseButtonEventArgs e)
{
Button aTargetButton = e.Source as Button;
if (aTargetButton != null)
{
aTargetButton.Background = Brushes.Azure;
aTargetButton.LayoutTransform = new RotateTransform(45);
if (myPreviouslyClickedButton != null)
{
myPreviouslyClickedButton.Background = Brushes.White;
myPreviouslyClickedButton.LayoutTransform = new RotateTransform(0);
}
myPreviouslyClickedButton = aTargetButton;
}
}
当我运行这些片段时,只有当我右键单击它时,相应的按钮才会进行角度转换(即使我订阅了MouseDown)。你能帮我解决这个问题吗?
更新
如果我用椭圆替换按钮,这个片段似乎有用。当椭圆可以时,为什么按钮不能对左击声做出反应。如果我再次单击相同的椭圆
,也不会引发事件答案 0 :(得分:1)
按钮处理鼠标按下事件。
如果您希望网格处理按钮事件,那么您可能会执行以下操作:
<ScrollViewer VerticalScrollBarVisibility="Auto">
<UniformGrid Button.Click="UniformGrid_Click">
<Button x:Name="Button1" Margin="10">1</Button>
<Button x:Name="Button2">2</Button>
<Button x:Name="Button3">3</Button>
<Button x:Name="Button4">4</Button>
<Button x:Name="Button5">5</Button>
<Button x:Name="Button6">6</Button>
<Button x:Name="Button7">7</Button>
<Button x:Name="Button8">8</Button>
<Button x:Name="Button9">9</Button>
</UniformGrid>
</ScrollViewer>
并将源更改为:
private void UniformGrid_Click(object sender, RoutedEventArgs e)
{
// Your code here
}
有一篇msdn文章here值得一读。
答案 1 :(得分:0)
这是正常的。在内部,Button
会处理MouseDown
事件,以了解何时触发其Click
事件。我发现Snoop是一个很好的工具,可用于跟踪WPF事件的问题,或者只是更好地了解它们的工作原理。