Search code examples
silverlightwindows-phonerouted-events

Prevent hyperlink Click event from bubbling up


I'm designing a windows Phone app. I have a Hyperlink object in a RichTextBox, in a Grid. The Grid had a Tap event, and the Hyperlink has a Click event.

Clicking the Hyperlink also raises the parent Grid's Tap event. How can I prevent this?

I would use e.Handled in the Click handler, but RoutedEventArgs do not have a Handled property in Silverlight for Windows Phone... I also tried walking the logical tree to look for the original source, but the click appears to originate from a MS.Internal.RichTextBoxView control (e.OriginalSource)...


Solution

  • I don't think there is any good way from within the Click handler itself. The following state management can work though:

    XAML:

    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" Tap="ContentPanel_Tap_1">
        <RichTextBox Tap="RichTextBox_Tap_1">
           <Paragraph>
               fdsfdfdf
               <Hyperlink Click="Hyperlink_Click_1">fdsfdsfsaf</Hyperlink>
               fsdfsdfa
           </Paragraph>
       </RichTextBox>
    </Grid>
    

    and the code:

    bool RtbTapHandled = false;
    
    private void Hyperlink_Click_1(object sender, RoutedEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Hyperlink");
        RtbTapHandled = true;
    }
    
    private void RichTextBox_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
    {
        if (RtbTapHandled)
        {
            e.Handled = true;
        }
    
        RtbTapHandled = false;
        System.Diagnostics.Debug.WriteLine("RTB_Tap");
    }
    
    private void ContentPanel_Tap_1(object sender, System.Windows.Input.GestureEventArgs e)
    {
        System.Diagnostics.Debug.WriteLine("Content_Tap");
    }
    

    In this case if you click on the RichTextBox you'll get callbacks from both RichTextBox_Tap_1 and ContentPanel_Tap_1, but if you click on the Hyperlink you'll get Hyperlink_Click_1 and RichTextBox_Tap_1 though it'll be handled at that level and stopped.