3

I have a Link in Richtextbox and it works good but if I save that Richtextbox in to database and then load it that link to be deleted and I just can see the text of that Link

for example my Richtextbox have bottom text:

This is a link

But after save and load again I just can see the text:

This is a link

The hyperlink created dynamically from selected text as bellow:

            RichTextBox.IsDocumentEnabled = true;

            RichTextBox.IsReadOnly = true;

            Run run = new Run(RichTextBox.Selection.Text);
            Hyperlink hyp = new Hyperlink(run) { TargetName = run.Text };
            TERM.WordMain main = new TERM.WordMain();

            hyp.Click += new RoutedEventHandler(main.hyperLink_Click);
            hyp.NavigateUri = new Uri("http://search.msn.com");
            RichTextBox.Cut();

            var container = new InlineUIContainer(new TextBlock(hyp), RichTextBox.Selection.Start);
            RichTextBox.IsDocumentEnabled = true;
            RichTextBox.IsReadOnly = false;

Saving richtextbox content as RTF format to text field:

 public static string ToStringFromBytes(System.Windows.Controls.RichTextBox richTextBox)
    {
        if (richTextBox.Document.Blocks.Count == 0)
        {
            return null;
        }

        MemoryStream memoryStream = new MemoryStream();

        TextRange textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);

        textRange.Save(memoryStream, System.Windows.DataFormats.Rtf);

        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }

And load from database to flowdocument

public static FlowDocument LoadFromString(string s)
    {
        try
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(s);

            MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(s));

            FlowDocument doc = new FlowDocument();

            TextRange textRange = new TextRange(doc.ContentStart, doc.ContentEnd);

            textRange.Load(stream, System.Windows.DataFormats.Rtf);

            return doc;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
Elvin Mammadov
  • 25,329
  • 11
  • 40
  • 82
  • I add some codes for example. – Elvin Mammadov Jan 04 '16 at 12:14
  • Does the `Paragraph` object get stored with the `Hyperlink` in the collection along with the other `Run` objects? This will tell you whether it's the save or load code that's failing. – ChrisF Jan 04 '16 at 12:24
  • @ChrisF, I cant understand the question. – Elvin Mammadov Jan 04 '16 at 12:31
  • Do you just store the text or do you store the XAML markup as well? – ChrisF Jan 04 '16 at 12:33
  • First of all i save as Xaml format,, But after this I lost hyperlink. Then I search and find that for saving hyperlinks or images to database it must save in RTF format as string,, but after this I lost link ability of hyperlinks – Elvin Mammadov Jan 04 '16 at 12:36
  • I have an application where I save the xaml and it all works fine. You need to use the RichTextBox's `Xaml` property when reading from it or setting it up. – ChrisF Jan 04 '16 at 12:41
  • ok, First application work. But after this problem http://stackoverflow.com/questions/34434975/showing-database-rtf-data-in-richtextbox I change functinality of its. So then I can't save data as xaml because I lost hyper link. – Elvin Mammadov Jan 04 '16 at 12:43
  • @ChrisF, I add hyperlink yo word document, and then save and load it. Hyperlink is shown. I think that there is a problem in creating dynamic hyperlink – Elvin Mammadov Jan 04 '16 at 13:02

1 Answers1

4

The following sample seems to do the trick.

Here I load and save the XAML instead of the text in rtf format. Note also that you need to add handlers for the hyperlinks back to the elements after loading, since they will not be serialized.

public partial class MainWindow : Window
{
    private const string _stateFile = "state.xaml";
    public MainWindow()
    {
        InitializeComponent();
        richTextBox.IsReadOnly = false;
    }

    private void createLinkButton_Click(object sender, RoutedEventArgs e)
    {
        richTextBox.IsDocumentEnabled = false;
        richTextBox.IsReadOnly = true;
        var textRange = richTextBox.Selection;
        var hyperlink = new Hyperlink(textRange.Start, textRange.End);
        hyperlink.TargetName = "value";
        hyperlink.NavigateUri = new Uri("http://search.msn.com");
        hyperlink.RequestNavigate += HyperlinkOnRequestNavigate;
        richTextBox.IsDocumentEnabled = true;
        richTextBox.IsReadOnly = false;
    }

    private void HyperlinkOnRequestNavigate(object sender,
        RequestNavigateEventArgs args)
    {
        // Outputs: "Requesting: http://search.msn.com, target=value" 
        Console.WriteLine("Requesting: {0}, target={1}", args.Uri, args.Target);
    }

    private void SaveXamlPackage(string filePath)
    {
        var range = new TextRange(richTextBox.Document.ContentStart,
            richTextBox.Document.ContentEnd);
        var fStream = new FileStream(filePath, FileMode.Create);
        range.Save(fStream, DataFormats.XamlPackage);
        fStream.Close();
    }

    void LoadXamlPackage(string filePath)
    {
        if (File.Exists(filePath))
        {
            var range = new TextRange(richTextBox.Document.ContentStart,
                richTextBox.Document.ContentEnd);
            var fStream = new FileStream(filePath, FileMode.OpenOrCreate);
            range.Load(fStream, DataFormats.XamlPackage);
            fStream.Close();
        }

        // Reapply event handling to hyperlinks after loading, since these are not saved:
        foreach (var paragraph in richTextBox.Document.Blocks.OfType<Paragraph>())
        {
            foreach (var hyperlink in paragraph.Inlines.OfType<Hyperlink>())
            {
                hyperlink.RequestNavigate += HyperlinkOnRequestNavigate;
            }
        }
    }

    private void saveButton_Click(object sender, RoutedEventArgs e)
    {
        SaveXamlPackage(_stateFile);
    }

    private void loadButton_Click(object sender, RoutedEventArgs e)
    {
        LoadXamlPackage(_stateFile);
    }
}
steinar
  • 9,383
  • 1
  • 23
  • 37