Search code examples
c#xamlwindows-store-appswindows-8.1richtextblock

RichTextBlock PointerPressedEvent - pointer position when selecting a text


I am developping a windows store application. In my page, I have a RichTextBlock (and not a RichTextBox as in WPF).

I'd like to subscribe to the PointerPressed event. In my constructor, I have the following

   rtb.PointerPressed += RtbOnPointerPressed;
    rtb.PointerReleased += RtbOnPointerReleased;

My problem is that these events are never fired.

If I put a grid on top of my RichTextBlock (TopGrid in my code), I can capture the pointerPressed event. However, I can no longer select a text in my RichTextBlock.

If I try to capture the pointerPressed event at the container level (Container in the code below), it works on if I press in the margins not when I select a text.

    <Grid x:Name="Container">//at this level, pointerPressed is raised
           //only when I click outside the richtextblock

       <RichTextBlock x:Name="rtb"></RichTextBlock>//PointerPressed is never fired
       <Grid Background="Transparent" x:Name="TopGrid"></Grid>//If present,
       //the selection does not work on RichTextBlock" 
       //but I can capture the pointerPressed event
    </Grid>

Does anyone here know how to know the pointer position when selecting a text?


Solution

  • You have to handle SelectionChanged event. Sender will have SelectionStart, SelectionEnd and SelectedText properties.

    If you for some reason want to use Pressed/Released events replace your code with:

    rtb.AddHandler(PointerPressedEvent, new PointerEventHandler(RtbOnPointerPressed), true);

    rtb.AddHandler(PointerReleasedEvent, new PointerEventHandler(RtbOnPointerReleased), true);

    The last parameter handledEventsToo has to be set to true to make sure that the handler will be invoked even if the event is handled somewhere else.

    According to https://msdn.microsoft.com/pl-pl/library/windows/apps/xaml/windows.ui.xaml.uielement.pointerpressed you should be aware of the fact that PointerPressed and PointerReleased are not always occuring in pairs.