Code behind:
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 Microsoft.Win32;
using System.Globalization;
namespace WpfApplication54
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.AddHandler(AttachedEventTest.NeedsCleaningEvent, new RoutedEventHandler((object o, RoutedEventArgs e) => { MessageBox.Show("from window"); }));
// use true to handle this event too in MainWindow level though e.handled is marked as true in grid_NeedsCleaning method.
//this.AddHandler(AttachedEventTest.NeedsCleaningEvent, new RoutedEventHandler((object o, RoutedEventArgs e) => { MessageBox.Show("from window"); }), true);
}
private void button1_Click(object sender, RoutedEventArgs e)
{
this.grid.RaiseEvent(new RoutedEventArgs(AttachedEventTest.NeedsCleaningEvent));
}
private void grid_NeedsCleaning(object sender, RoutedEventArgs e)
{
MessageBox.Show("from grid");
//e.Handled = true;
}
}
// for this case, note that, if NeedsCleaningEvent's RoutingStrategy is Bubble, the order of windows pop up is: from grid -> from window(frist catched by grid, then window);
// if NeedsCleaningEvent's RoutingStrategy is Tunnel, the order of windows pop up is: from window -> from grid;
public class AttachedEventTest
{
// below is the pattern of AttachedEvent, it uses the same method RegisterRoutedEvent as non-attached event.
// the Add*Handler and Remove*Handler are must, xaml will use it when setting attached event for an element in xaml.
public static readonly RoutedEvent NeedsCleaningEvent = EventManager.RegisterRoutedEvent("NeedsCleaning", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(AttachedEventTest));
public static void AddNeedsCleaningHandler(DependencyObject d, RoutedEventHandler handler)
{
UIElement uie = d as UIElement;
if (uie != null)
{
uie.AddHandler(AttachedEventTest.NeedsCleaningEvent, handler);
}
}
public static void RemoveNeedsCleaningHandler(DependencyObject d, RoutedEventHandler handler)
{
UIElement uie = d as UIElement;
if (uie != null)
{
uie.RemoveHandler(AttachedEventTest.NeedsCleaningEvent, handler);
}
}
}
}
Xaml:
<Window x:Class="WpfApplication54.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525"
xmlns:local="clr-namespace:WpfApplication54">
<Grid x:Name="grid" local:AttachedEventTest.NeedsCleaning="grid_NeedsCleaning" >
<Button Content="Button1" Click="button1_Click" Height="23" HorizontalAlignment="Left" Margin="174,118,0,0" Name="button1" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>