Hyperlink in RichTextBlock makes the application c

2019-08-09 23:11发布

问题:

in my Windows Phone 8.1 application I have a RichTextBlock with Hyperlinks in it. I've added some block of code in the click event of the Hyperlink. The problem is that whenever I click on the Hyperlink, my application crashes with an 'Access Violation' exception. This only happens when the keyboard is visible. If the keyboard is resigned then I do not get the exception. Also, this only happens on a WP8.1 device and not a W10 device. Below is my code.

XAML

<StackPanel>
    <RichTextBlock FontSize="40" x:Name="rtb"/>
    <TextBox x:Name="tb"/>
</StackPanel>

Code behind

void MainPage_Loaded(object sender, RoutedEventArgs e)
{
    rtb.Blocks.Add(ContentForRichTextBox("9910918444"));
}

This is how I'm building the content for the RichTextBox

public Paragraph ContentForRichTextBox(string plainString)
{
    Paragraph richContent = new Paragraph();
    try
    {
        string[] plainStringSplit = plainString.Split(' ');
        foreach (var word in plainStringSplit)
        {
            var number = new Hyperlink();
            number.Foreground = new SolidColorBrush(Colors.DarkBlue);
            number.Inlines.Add(new Run { Text = word });
            number.Click += (s, e) =>
            {
                try
                {
                    Windows.ApplicationModel.Calls.PhoneCallManager.ShowPhoneCallUI(word, "Some dude");
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Debug.WriteLine("Exception HelperMethod   number.Click : " + ex.ToString());
                }
            };
            richContent.Inlines.Add(number);

            //add a space
            if (plainStringSplit.Last() != word)
            {
                richContent.Inlines.Add(new Run { Text = " " });
            }
        }
    }
    catch (Exception ex)
    {
        System.Diagnostics.Debug.WriteLine("Exception HelperMethod ContentForRichTextBox : " + ex.ToString());
    }
    return richContent;
}

Whenever I click on the Hyperlink and my TextBox is in focus, the application crashes with the exception

The program '[2992] App5.exe' has exited with code -1073741819 (0xc0000005) 'Access violation'.

Any help would be greatly appreciated.

回答1:

I had the same problem on a WP8.1 app with the HyperLink causing an Access Violation. I get a workaround using am HyperlinkButton instead of an Hyperlink. To add an HyperlinkButton you need to contain it inside an inlineUIContainer element this way:

InlineUIContainer uiContainer = new InlineUIContainer();
HyperlinkButton b = new HyperlinkButton();
b.Content = runText.Text;
b.NavigateUri = uri;
b.Tag = uri;
b.Click += (s, args) =>
{
    //Your click logic here.
};
uiContainer.Child = b;
paragraph.Inlines.Add(uiContainer);

Hope this helps you also!