如何在没有丢失链接的数据库中保存WPF RichTextBox? [英] How can I save WPF RichTextBox in databse without lost links?

查看:139
本文介绍了如何在没有丢失链接的数据库中保存WPF RichTextBox?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Richtextbox中有一个链接并且它运行良好但是如果我将Richtextbox保存到数据库中,然后加载该链接以进行删除,我只能看到该链接的文本

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

例如我的Richtextbox有底部文字:

for example my Richtextbox have bottom text:

这是一个链接

但是在保存并再次加载之后我才能看到文字:

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

这个是一个链接

从所选文本动态创建的超链接如下:

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;

将RTF格式的richtextbox内容保存到文本字段:

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());
    }

从数据库加载到 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;
        }
    }


推荐答案

以下示例似乎可以解决问题。

The following sample seems to do the trick.

这里我加载并保存 XAML 而不是rtf格式的文本。另请注意,您需要在加载后将超链接的处理程序添加回元素,因为它们不会被序列化。

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);
    }
}

这篇关于如何在没有丢失链接的数据库中保存WPF RichTextBox?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆