由於事件冒泡,下面的代碼應該將表單中存在的所有按鈕變成綠色,但是在我的Visual Studio 2008機器上,它是隻把點擊的按鈕變成綠色,你能幫忙解決問題嗎?需要幫助理解WPF中的事件冒泡代碼
XAML代碼(window1.xaml):
<Window x:Class="EventRouting.Window1" Title="Event Routing" Height="300" Width="300"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Border Margin="15" BorderBrush="Blue" BorderThickness="5" Padding="15"
CornerRadius="12" x:Name="myBorder" Background="Transparent">
<StackPanel x:Name="myPanel" Background="Transparent">
<Ellipse x:Name="myEllipse" Margin="3" Fill="Green" Height="40" />
<Rectangle x:Name="myRectangle" Margin="3" Fill="Cyan" Height="40" RadiusX="10" RadiusY="10" />
</StackPanel>
CS代碼(window1.xaml.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;
namespace EventRouting
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.MouseEnter += MouseEnterHandler;
myBorder.MouseEnter += MouseEnterHandler;
myPanel.MouseEnter += MouseEnterHandler;
myEllipse.MouseEnter += MouseEnterHandler;
myRectangle.MouseEnter += MouseEnterHandler;
this.MouseDown += MouseDownHandler;
myBorder.MouseDown += MouseDownHandler;
myPanel.MouseDown += MouseDownHandler;
myEllipse.MouseDown += MouseDownHandler;
myRectangle.MouseDown += MouseDownHandler;
for (int i = 1; i <= 5; ++i)
{
Button btn = new Button();
btn.Content = "Button " + i;
myPanel.Children.Add(btn);
//btn.Click += new RoutedEventHandler(btn_Click);
}
myPanel.AddHandler(Button.ClickEvent, new RoutedEventHandler(btn_Click));
}
void btn_Click(object sender, RoutedEventArgs e)
{
Button btn = (Button) e.Source;
btn.Background = Brushes.Green;
}
void MouseEnterHandler(object sender, MouseEventArgs e)
{
Debug.WriteLine("MouseEnter: " + sender);
}
void MouseDownHandler(object sender, MouseButtonEventArgs e)
{
Debug.WriteLine("MouseDown: " + sender);
e.Handled = true;
}
}
}
但事件正在添加到myPanel(stackPanel),它保留所有的按鈕,所以它應該適用於所有的按鈕? – mohits00691