Friday, August 12, 2011

Attached Routed Event in WPF


WPF also supports Attached Routed Events. This is useful while tunneling and bubbling event through elements which don’t define that event. Routed Event can be used as an attached event. Attached events are much similar to Attached Properties. Attached properties use Property value inheritance while Attached events use bubbling and tunneling. Let’s understand Attached Event with simple example.

<Grid Button.Click="Grid_Click">
    <StackPanel Button.Click="StackPanel_Click">
        <Button Content="Click Me!" Height="35" Width="150"
        Margin="5" />
    </StackPanel>
</Grid>

private void StackPanel_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Stackpanel");
}

private void Grid_Click(object sender, RoutedEventArgs e)
{
    MessageBox.Show("Grid");
}














On Button Click event, it bubbled up the event to top element. StackPanel and Grid doesn’t define their own Click event. So Button.Click (Attached Routed Event) is defined on StackPanel and Grid. So when user clicks on Button, it will call StackPanel_Click first and followed by Grid_Click event.


Related links –

No comments:

Post a Comment