private void GenerateQRCodeAndLink(dynamic state) { var qrcode = new QRCodeWriter(); var price = (decimal)state.price / DNotesToSatoshi; var address = (string)state.address; var qrValue = string.Format("dnotes:{0}?amount={1}&invoice={2}", address, price, state.invoice); var priceUSD = (decimal)state.priceUSD; var invoice = (string)state.invoice; var payText = string.Format("<strong>Please send exactly:</strong> {0:0.00000000} NOTE <a href='" + CopyAmtUrl + "'>copy</a><br/>" + "<strong>To:</strong> {1}+{2} <a href='" + CopyAddrUrl + "'>copy</a>", price, address, invoice); usdLabel.Content = string.Format("USD: ${0:0.00}", priceUSD); var xaml = HtmlToXamlConverter.ConvertHtmlToXaml(payText, true); dynamic flowDocument = XamlReader.Parse(xaml); HyperlinkEvents(flowDocument); payLabel.Document = flowDocument; var barcodeWriter = new BarcodeWriter { Format = BarcodeFormat.QR_CODE, Options = new EncodingOptions { Height = 300, Width = 300, Margin = 1 } }; using (var bitmap = barcodeWriter.Write(qrValue)) using (var stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Png); BitmapImage bi = new BitmapImage(); bi.BeginInit(); stream.Seek(0, SeekOrigin.Begin); bi.StreamSource = stream; bi.CacheOption = BitmapCacheOption.OnLoad; bi.EndInit(); qrCodeImage.Source = bi; } }
private List <RssItem> RefreshNewsAsych(string strUrl) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strUrl); req.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)"; WebResponse resp = req.GetResponse(); Stream strIn = resp.GetResponseStream(); StreamReader read = new StreamReader(strIn); string re = read.ReadToEnd(); List <RssItem> lstRss = new List <RssItem>(); //load the feed try { XElement theRoot = XElement.Parse(re); if (theRoot != null) { //get the channel XElement theChannel = theRoot.Element("channel"); if (theChannel != null) { //get the item elements var theItems = from ele in theChannel.Elements("item") select new RssItem { Title = ele.Element("title").Value, Description = HtmlToXamlConverter.ConvertHtmlToXaml(ele.Element("description").Value, true), Link = ele.Element("link").Value, Published = DateTime.Parse(ele.Element("pubDate").Value) }; lstRss = theItems.ToList(); } } } catch (Exception ex) { } return(lstRss); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value != null) { FlowDocument flowDocument = new(); string xaml = HtmlToXamlConverter.ConvertHtmlToXaml(value.ToString(), false); using (MemoryStream stream = new(new ASCIIEncoding().GetBytes(xaml))) { TextRange text = new(flowDocument.ContentStart, flowDocument.ContentEnd); text.Load(stream, DataFormats.Xaml); } return(flowDocument); } return(value); }
public void SetText(System.Windows.Documents.FlowDocument document, string text) { text = HtmlToXamlConverter.ConvertHtmlToXaml(text, false); try { TextRange tr = new TextRange(document.ContentStart, document.ContentEnd); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text))) { tr.Load(ms, DataFormats.Xaml); } } catch { throw new InvalidDataException("data provided is not in the correct Html format."); } }
public void accentText(string text, TextDataFormat format) { if (format == TextDataFormat.Html) { text = text.Substring(text.IndexOf('<')); StringBuilder sb = new StringBuilder(); sb.Append(HtmlToXamlConverter.ConvertHtmlToXaml(text, true)); richTextBox.Document = (FlowDocument)XamlReader.Parse(sb.ToString()); } if (format == TextDataFormat.Rtf) { MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(text)); TextRange range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); range.Load(stream, DataFormats.Rtf); } if (format == TextDataFormat.Text) { richTextBox.AppendText(text); } }
private FlowDocument ConvertHtmlToFlowDocument(string html) { var xaml = HtmlToXamlConverter.ConvertHtmlToXaml(html, false); var flowDocument = new FlowDocument(); using (var stream = new MemoryStream((new UTF8Encoding()).GetBytes(xaml))) { var text = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd); text.Load(stream, DataFormats.Xaml); } SubscribeToAllHyperlinks(flowDocument); flowDocument.FontSize = SystemFonts.IconFontSize; flowDocument.FontWeight = SystemFonts.MessageFontWeight; flowDocument.FontFamily = SystemFonts.CaptionFontFamily; return(flowDocument); }
internal override System.Windows.Documents.FlowDocument GetKnowledgeDefinition() { if (this.assessmentApp.Knowledge.Content == null) { return(new System.Windows.Documents.FlowDocument()); } if (this.assessmentApp.Knowledge.Content.ContentType == Assessment.Data.ContentType.Html) { return(HtmlToXamlConverter.ConvertHtmlToXaml(this.assessmentApp.Knowledge.Content.Content)); } else if (this.assessmentApp.Knowledge.Content.ContentType == Assessment.Data.ContentType.FlowDocument) { FlowDocument doc = HtmlToXamlConverter.DeserializeFlowDocument(this.assessmentApp.Knowledge.Content.Content); CommonControlCreator.replaceTextBoxWithRichTextBox(doc, this.assessmentApp.Knowledge.Content, null); return(doc); } throw new NotSupportedException("Knowledge must be HTML or FlowDocument format!"); }
private static void OnHtmlTextChanged( DependencyObject depObj, DependencyPropertyChangedEventArgs e) { // Go ahead and return out if we set the property on something other than a textblock, or set a value that is not a string. var txtBox = depObj as TextBlock; if (txtBox == null) { return; } if (!(e.NewValue is string)) { return; } var html = e.NewValue as string; string xaml; InlineCollection xamLines; try { xaml = HtmlToXamlConverter.ConvertHtmlToXaml(html, false); xamLines = ((Paragraph)((Section)System.Windows.Markup.XamlReader.Parse(xaml)).Blocks.FirstBlock).Inlines; } catch { // There was a problem parsing the html, return out. return; } // Create a copy of the Inlines and add them to the TextBlock. Inline[] newLines = new Inline[xamLines.Count]; xamLines.CopyTo(newLines, 0); txtBox.Inlines.Clear(); foreach (var l in newLines) { txtBox.Inlines.Add(l); } }
/// <summary> /// Default constructor /// </summary> public UserControlCelestrakPage() { InitializeComponent(); WebRequest request = WebRequest.Create("http://celestrak.com/NORAD/elements/"); try { WebResponse resp = request.GetResponse(); using (TextReader reader = new StreamReader(resp.GetResponseStream())) { string xaml = HtmlToXamlConverter.ConvertHtmlToXaml(reader.ReadToEnd(), true); System.Xml.XmlDocument doc = new System.Xml.XmlDocument(); doc.LoadXml(xaml); XmlNodeList nl = doc.GetElementsByTagName("Hyperlink"); List <XmlElement> ln = new List <XmlElement>(); foreach (XmlElement e in nl) { ln.Add(e); } foreach (XmlElement e in ln) { string s = e.GetAttribute("NavigateUri"); if (s.Contains('@')) { e.ParentNode.RemoveChild(e); } } xaml = doc.OuterXml; object el = XamlReader.Parse(xaml); Content = el; this.RecursiveAction <Hyperlink>(ProcessLink); } } catch (Exception exception) { exception.ShowError(10); } }
public void SetText(FlowDocument document, string text) { var xaml = HtmlToXamlConverter.ConvertHtmlToXaml(text, false); try { if (String.IsNullOrEmpty(xaml)) { document.Blocks.Clear(); } else { TextRange tr = new TextRange(document.ContentStart, document.ContentEnd); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(xaml))) { tr.Load(ms, DataFormats.Xaml); } } } catch { throw new InvalidDataException("Data provided is not in the correct Xaml format."); } }
public void SetText(FlowDocument document, string text) { text = HtmlToXamlConverter.ConvertHtmlToXaml(text, false); try { TextRange tr = new TextRange(document.ContentStart, document.ContentEnd); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(text)); try { tr.Load(ms, DataFormats.Xaml); } finally { if (ms != null) { ((IDisposable)ms).Dispose(); } } } catch { throw new InvalidDataException("data provided is not in the correct Html format."); } }
/* * private static void ConvertRtfInSTAThread(object html) * { * var wb = new System.Windows.Forms.WebBrowser(); * wb.Navigate("about:blank"); * wb.Document.Encoding = Encoding.UTF8.WebName; * wb.Document.Write((string)html); * wb.Document.ExecCommand("SelectAll", false, null); * wb.Document.ExecCommand("Copy", false, null); * _result = (string)Clipboard.GetData(DataFormats.Rtf); * }*/ private static void ConvertRtfInSTAThread(object html) { try { var richTextBox = new RichTextBox(); var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); var xaml = HtmlToXamlConverter.ConvertHtmlToXaml((string)html, false); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xaml))) textRange.Load(stream, DataFormats.Xaml); textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); using (var stream = new MemoryStream()) { textRange.Save(stream, DataFormats.Rtf); stream.Position = 0; using (var streamReader = new StreamReader(stream)) _result = streamReader.ReadToEnd(); } } catch (Exception e) { _exception = e; _result = null; } }
public static string ConvertHtmlToRtf(string htmlText) { var xamlText = HtmlToXamlConverter.ConvertHtmlToXaml(htmlText, false); return(ConvertXamlToRtf(xamlText)); }
public void SpecifyPaperSet(GoogleScholarScrapePaperSet gssps) { DocsPanel.Children.Clear(); { // Add the header StackPanel sp = new StackPanel(); HyperlinkTextBlock tb_gs = new HyperlinkTextBlock(); tb_gs.HorizontalAlignment = HorizontalAlignment.Center; tb_gs.Text = "Go to GoogleScholar"; tb_gs.FontWeight = FontWeights.Bold; tb_gs.Tag = gssps.Url; tb_gs.OnClick += OpenUrlInTagOfTextBlock; sp.Children.Add(tb_gs); DocsPanel.Children.Add(sp); DocsPanel.Children.Add(new AugmentedSpacer()); } bool alternate = false; foreach (var gssp in gssps.Papers) { StackPanel sp = new StackPanel(); try { string html = gssp.abstract_html; html = html.Replace("<br>", " "); string xaml = HtmlToXamlConverter.ConvertHtmlToXaml(html, true); FlowDocument fd = (FlowDocument)XamlReader.Parse(xaml); RichTextBox rtb = new RichTextBox(fd); rtb.Width = 320; rtb.Height = 200; sp.ToolTip = rtb; } catch (Exception ex) { Logging.Warn(ex, "Problem parsing GS HTML abstract"); } if (null != gssp.source_url) { HyperlinkTextBlock tb_title = new HyperlinkTextBlock(); tb_title.Text = gssp.title; tb_title.Tag = gssp.source_url; tb_title.OnClick += OpenUrlInTagOfTextBlock; sp.Children.Add(tb_title); } else { TextBlock tb_title = new TextBlock(); tb_title.Text = gssp.title; tb_title.FontWeight = FontWeights.Bold; sp.Children.Add(tb_title); } TextBlock tb_authors = new TextBlock(); tb_authors.Text = gssp.authors; sp.Children.Add(tb_authors); TextBlock tb_citedby = new TextBlock(); tb_citedby.Text = gssp.cited_by_header; sp.Children.Add(tb_citedby); if (0 < DocsPanel.Children.Count) { DocsPanel.Children.Add(new AugmentedSpacer()); } alternate = !alternate; ListFormattingTools.AddGlowingHoverEffect(sp); DocsPanel.Children.Add(sp); } }
/// <summary> /// /// </summary> /// <param name="asFlowDocument"> /// true indicates that we need a FlowDocument as a root element; /// false means that Section or Span elements will be used /// dependeing on StartFragment/EndFragment comments locations. /// </param> public static string XamlStringFromHtml(this string str, bool asFlowDocument) { return(HtmlToXamlConverter.ConvertHtmlToXaml(str, asFlowDocument)); }
/// <summary> /// Converts Html string to Xaml string. Section or Span elements will be used as a root element /// </summary> public static string XamlStringFromHtml(this string str) { return(HtmlToXamlConverter.ConvertHtmlToXaml(str, false)); }
internal static System.Windows.Documents.Section CreateContentControl(QuestionContent content, string prefix, System.Windows.Documents.Section paragraph, Response response) { System.Windows.Documents.Section rootSection = paragraph; if (rootSection == null) { rootSection = new System.Windows.Documents.Section(); } if (content.ContentType == ContentType.Html || content.ContentType == ContentType.FlowDocument) { string doc = string.Empty; if (content.ContentType == ContentType.Html) { doc = HtmlToXamlConverter.ConvertHtmlToXaml(content.Content, true); } else { doc = content.Content; } System.Windows.Documents.FlowDocument flowDocument = HtmlToXamlConverter.DeserializeFlowDocument(doc); replaceTextBoxWithText(flowDocument, content, null); List <Block> tempList = new List <Block>(); tempList.AddRange(flowDocument.Blocks); flowDocument.Blocks.Clear(); rootSection.Blocks.AddRange(tempList); Paragraph firstPara = null; if (rootSection.Blocks.FirstBlock is Paragraph) { firstPara = rootSection.Blocks.FirstBlock as Paragraph; } else { firstPara = new Paragraph(); rootSection.Blocks.InsertBefore(rootSection.Blocks.FirstBlock, firstPara); } if (firstPara.Inlines.Count > 0) { firstPara.Inlines.InsertBefore(firstPara.Inlines.FirstInline, new Run(prefix)); } else { firstPara.Inlines.Add(prefix); } } else { Paragraph para = null; if (rootSection.Blocks.LastBlock is Paragraph) { para = rootSection.Blocks.LastBlock as Paragraph; } else { para = new Paragraph(); rootSection.Blocks.Add(para); } string questionContent = content.Content; int startIndex = 0; para.Inlines.Add(prefix); while (true) { startIndex = questionContent.IndexOf("_$", 0); if (startIndex >= 0) { int endIndex = questionContent.IndexOf("$_", startIndex); string placeHolder = questionContent.Substring(startIndex, endIndex - startIndex + 2); string text = questionContent.Substring(0, startIndex); if (!string.IsNullOrEmpty(text) && text[text.Length - 1] == '\n') { para.Inlines.Add(CreateText(text.Remove(text.Length - 1))); } else { para.Inlines.Add(CreateText(text)); } QuestionContentPart part = content.GetContentPart(placeHolder); if (response is FIBQuestionResponse) { FIBQuestionResponse fibResponse = response as FIBQuestionResponse; para.Inlines.Add(CreateUIPart(part, fibResponse.GetBlankResponse(part.Id, false))); } else { para.Inlines.Add(CreateUIPart(part, null)); } questionContent = questionContent.Remove(0, endIndex + 2); if (string.IsNullOrEmpty(questionContent)) { break; } } else { para.Inlines.Add(CreateText(questionContent)); break; } } } return(rootSection); }
/*private void CWB_IsBrowserInitializedChanged(object sender, DependencyPropertyChangedEventArgs e) * { * if (CWB.IsInitialized) * { * LoadFormattedPatchNotes(); * } * else * { * //not initialized * } * }*/ private void LoadFormattedPatchNotes() { // this version is used when rendering directly in HTML (e.g. webbrowser control or cefsharp) //string formattedPatchNotes = "<html><body style='background-color: #404040; font-family: sans-serif; color: #f8f8f8; font-size:90%;'>" + ProcessBBCodeFromTxtFile(patchnotes) + "</body></html>"; //WebBrowserControl.NavigateToString(formattedPatchNotes);//this is the integrated browser, which unfortunately doesn't render properly in transparent windows: //https://web.archive.org/web/20150415020527/http://blogs.msdn.com/b/changov/archive/2009/01/19/webbrowser-control-on-transparent-wpf-window.aspx //hence the unfortunate need to swap to another option e.g. CEF (much, much heavier than the integrated one though) //Console.WriteLine(formattedPatchNotes); //first check if file exists if (File.Exists(Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"mods/Community Balance Patch/patchnotes.txt")))) { try { // manually adding the hyperlink (and associated text) at the top (because flowdocuments don't handle URLs by default, even though they do display as if they do) // https://stackoverflow.com/questions/2288999/how-can-i-get-a-flowdocument-hyperlink-to-launch-browser-and-go-to-url-in-a-wpf Paragraph paragraph = new Paragraph(); myFlowDocument.Blocks.Add(paragraph); Run normaltext1 = new Run("These are only summaries with the most important details. Check the "); paragraph.Inlines.Add(normaltext1); Run linktext = new Run("Steam Workshop"); Hyperlink workshoplink = new Hyperlink(linktext); workshoplink.NavigateUri = new Uri("https://steamcommunity.com/sharedfiles/filedetails/changelog/2287791153"); workshoplink.RequestNavigate += new RequestNavigateEventHandler(Workshoplink_RequestNavigate); paragraph.Inlines.Add(workshoplink); //ensure to add linkname, not linktextname Run normaltext2 = new Run(" for links to the full patch notes."); paragraph.Inlines.Add(normaltext2); // patch notes - the main part of the flowdocument string patchnotes = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), @"mods/Community Balance Patch/patchnotes.txt"));//relies on CBP Launcher being in root folder (as expected) string formattedPatchNotes = "<html><body style='background-color: #4B101010; font-family: sans-serif; color: #C8C8C8;'>" + ProcessBBCodeFromTxtFile(patchnotes) + "</body></html>"; string xaml = HtmlToXamlConverter.ConvertHtmlToXaml(formattedPatchNotes, false); myFlowDocument.Blocks.Add((Section)XamlReader.Parse(xaml)); //because the document is larger than the pure HTML page was (in terms of visual space), the background needs to be set a bit differentl in order to cover the whole area: myFlowDocument.Background = (SolidColorBrush) new BrushConverter().ConvertFrom("#E2363636"); myFlowDocument.Foreground = (SolidColorBrush) new BrushConverter().ConvertFrom("#EEEEEE"); myFlowDocument.FontFamily = new FontFamily("Segoe UI"); myFlowDocument.FontSize = 15; myFlowDocument.PagePadding = new Thickness(10, 5, 10, 5); myFlowDocument.TextAlignment = TextAlignment.Left; FDViewer.Document = myFlowDocument; } catch (Exception ex) { // not sure if this catch will work, but it doesn't hurt to try FlowDocument myFlowDocument = new FlowDocument(); Paragraph myParagraph = new Paragraph(); myParagraph.Inlines.Add(new Run("Patch notes could not be loaded.\n\n" + ex)); myFlowDocument.Blocks.Add(myParagraph); FDViewer.Document = myFlowDocument; } } else { Paragraph paragraph = new Paragraph(); myFlowDocument.Blocks.Add(paragraph); Run normaltext1 = new Run("Unable to load patch notes file (maybe CBP isn't loaded)."); paragraph.Inlines.Add(normaltext1); myFlowDocument.Background = (SolidColorBrush) new BrushConverter().ConvertFrom("#E2363636"); myFlowDocument.Foreground = (SolidColorBrush) new BrushConverter().ConvertFrom("#EEEEEE"); myFlowDocument.FontFamily = new FontFamily("Segoe UI"); myFlowDocument.FontSize = 15; myFlowDocument.PagePadding = new Thickness(10, 5, 10, 5); FDViewer.Document = myFlowDocument; } //CWB.LoadHtml(formattedPatchNotes);//throws a debugging error on exit, but for now I simply don't care enough to fix it (I assume it's because cwb isn't being shut down correctly) }
public string ConvertXamlToHtml(string xamlText) { //return HtmlToXamlConverter.ConvertXamlToHtml(xamlText, false); return(HtmlToXamlConverter.ConvertHtmlToXaml(xamlText, false)); }
/// <summary> /// Converts the given html document to its flow document representation. /// </summary> /// <param name="htmlDocument">Html document to convert.</param> /// <param name="conversionResult">Conversion result to store error and warning messages.</param> /// <param name="vModellDirectory">Directory of the v-modell.</param> /// <returns>Flow document representing the given html document.</returns> public static string ConvertToFlowDocument(HtmlDocument htmlDocument, Tum.PDE.ToolFramework.Modeling.ValidationResult conversionResult, string vModellDirectory) { string flowDocument = HtmlToXamlConverter.ConvertHtmlToXaml(htmlDocument, conversionResult, vModellDirectory); return(flowDocument); }
public string ConvertHtmlToXaml(string htmlText) { return(HtmlToXamlConverter.ConvertHtmlToXaml(htmlText, asFlowDocument: true)); }
public void SetText(double position) { //HtmlToXamlConverter.ConvertHtmlToXaml(, true) OutlineTextSub.Text = HtmlToXamlConverter.ConvertHtmlToXaml(SubtitleFileCompiler.GetSubtitle(position), true); }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return(value); } FlowDocument flowDocument = new FlowDocument(); using (MemoryStream memoryStream = new MemoryStream(new UTF8Encoding().GetBytes(HtmlToXamlConverter.ConvertHtmlToXaml(value.ToString(), false)))) new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd).Load((Stream)memoryStream, DataFormats.Xaml); this.SubscribeToAllHyperlinks(flowDocument); flowDocument.FontStyle = FontStyles.Italic; flowDocument.FontSize = SystemFonts.MessageFontSize; flowDocument.FontFamily = SystemFonts.MessageFontFamily; return((object)flowDocument); }
public void convertContent(object sender, RoutedEventArgs e) { myTextBox.Text = HtmlToXamlConverter.ConvertHtmlToXaml(myTextBox.Text, true); MessageBox.Show("Content Conversion Complete!"); }
private string GetText(double position) { return(HtmlToXamlConverter.ConvertHtmlToXaml(SubtitleFileCompiler. GetSubtitle(position), true)); }
/// <summary> /// Load a rich text box by converting encoded HTML to XAML /// - /// Content maybe plain text -OR- GP-style tags /// GP-style tags are converted first and are subsequently lost /// </summary> /// <param name="sender"></param> /// <param name="context"></param> public static void LoadRichTextbox(object sender, object context) { IEnumerable <XmlNode> xmlNodes = Utils.GetXmlDataContext(context); if (null == xmlNodes) { return; } string xaml = null; // Load from encoded HTML foreach (XmlNode node in xmlNodes) { string htmlString = ""; // Check for existing XML child nodes XmlNodeList children = node.SelectNodes("*"); if (null != children && 0 < children.Count) { string xml = node.InnerXml; // Convert htmlString = ConvertToolXML(xml); // Write back to node the updated encoded xml node.InnerText = HttpUtility.HtmlEncode(htmlString); } else { // Inside element // May be encoded markup // InnerText decodes htmlString = node.InnerText.Trim(); if (0 != htmlString.IndexOf("<")) // does NOT have encoded markup { // Wrap the XML // Preserve non-tag entities string xmlString = node.InnerXml.Trim(); htmlString = "<DIV>" + xmlString + "</DIV>"; // InnerText encodes node.InnerText = htmlString; } } // node.InnerText does the decoding for us xaml = HtmlToXamlConverter.ConvertHtmlToXaml(node.InnerText, false); break; // Only one } // Now read the new XAML and add to the rich text box if (null != xaml && 0 < xaml.Length) { RichTextBox box = sender as RichTextBox; box.Document.Blocks.Clear(); using (MemoryStream xamlMemoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xaml))) { ParserContext parser = new ParserContext(); parser.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation"); parser.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml"); try { Section section = XamlReader.Load(xamlMemoryStream, parser) as Section; box.Document.Blocks.Add(section); } catch { } } } }
public static Panel CreateContentControl(QuestionContent content, Panel contentPanel, Brush foreground, ContentPartCreated contentPartCreated) { Panel stackPanel = contentPanel; if (stackPanel == null) { stackPanel = new StackPanel(); ((StackPanel)stackPanel).Orientation = Orientation.Vertical; } if (content.ContentType == ContentType.Html || content.ContentType == ContentType.FlowDocument) { FlowDocumentScrollViewer documentViewer = new FlowDocumentScrollViewer(); documentViewer.FocusVisualStyle = null; documentViewer.VerticalContentAlignment = VerticalAlignment.Center; documentViewer.VerticalAlignment = VerticalAlignment.Center; documentViewer.HorizontalContentAlignment = HorizontalAlignment.Left; documentViewer.VerticalScrollBarVisibility = ScrollBarVisibility.Auto; documentViewer.Background = Brushes.Transparent; documentViewer.FontSize = 20; FlowDocument document = null; if (content.ContentType == ContentType.Html) { document = HtmlToXamlConverter.ConvertHtmlToXaml(content.Content); } else { document = HtmlToXamlConverter.DeserializeFlowDocument(content.Content); } replaceTextBoxWithRichTextBox(document, content, contentPartCreated); document.FontSize = 20; documentViewer.Document = document; stackPanel.Children.Add(documentViewer); } else { string questionContent = content.Content; if (string.IsNullOrEmpty(questionContent)) { return(stackPanel); } int startIndex = 0; StackPanel itemPanel = new StackPanel(); itemPanel.Orientation = Orientation.Horizontal; stackPanel.Children.Add(itemPanel); bool newLine = false; while (true) { startIndex = questionContent.IndexOf("_$", 0); if (startIndex >= 0) { int endIndex = questionContent.IndexOf("$_", startIndex); string placeHolder = questionContent.Substring(startIndex, endIndex - startIndex + 2); string text = questionContent.Substring(0, startIndex); if (!string.IsNullOrEmpty(text)) { string[] textParts = text.Split(new char[] { '\n' }); if (textParts.Length > 1) { for (int i = 0; i < textParts.Length; i++) { string temp = textParts[i]; itemPanel.Children.Add(CreateText(temp, foreground)); if (i == textParts.Length - 1) { break; } StackPanel nextItemPanel = new StackPanel(); nextItemPanel.Orientation = Orientation.Horizontal; stackPanel.Children.Add(nextItemPanel); itemPanel = nextItemPanel; } } else { itemPanel.Children.Add(CreateText(text, foreground)); } } //else //{ // string[] textParts = text.Split(new char[] { '\n' }); // if (textParts.Length > 1) // { // foreach (string temp in textParts) // { // itemPanel.Children.Add(CreateText(temp)); // StackPanel nextItemPanel = new StackPanel(); // nextItemPanel.Orientation = Orientation.Horizontal; // stackPanel.Children.Add(nextItemPanel); // itemPanel = nextItemPanel; // } // } // else // { // itemPanel.Children.Add(CreateText(text)); // } //} if (newLine) { StackPanel nextItemPanel = new StackPanel(); nextItemPanel.Orientation = Orientation.Horizontal; stackPanel.Children.Add(nextItemPanel); itemPanel = nextItemPanel; } newLine = false; QuestionContentPart part = content.GetContentPart(placeHolder); UIElement element = CommonControlCreator.CreateUIPart(part, foreground); itemPanel.Children.Add(element); if (contentPartCreated != null) { contentPartCreated(element); } questionContent = questionContent.Remove(0, endIndex + 2); if (string.IsNullOrEmpty(questionContent)) { break; } } else { string[] textParts = questionContent.Split(new char[] { '\n' }); foreach (string text in textParts) { itemPanel.Children.Add(CreateText(text, foreground)); StackPanel nextItemPanel = new StackPanel(); nextItemPanel.Orientation = Orientation.Horizontal; stackPanel.Children.Add(nextItemPanel); itemPanel = nextItemPanel; } break; } } } return(stackPanel); }
public string ConvertHtmlToXaml(string htmlText) { return(HtmlToXamlConverter.ConvertHtmlToXaml(htmlText, true)); }
public void LoadData(BaseItem bi) { MainBody.Inlines.Clear(); var doms = bi.Comments; string link = string.Empty; bool flag = false; string _preFile = $"<{GlobalLanguage.Text_FilePref}"; string _preImage = $"<{GlobalLanguage.Text_ImagePref}"; string _preLink = $"<{GlobalLanguage.Text_LinkPref}"; for (int i = 0; i < doms.Count; i++) { if (doms[i].Length == 0) { MainBody.Inlines.Add(new LineBreak()); } else if (doms[i].StartsWith(_preFile) || doms[i].StartsWith(_preImage)) { MainBody.Inlines.Add(new Run(doms[i]) { Foreground = Brushes.LightSeaGreen }); MainBody.Inlines.Add(new LineBreak()); } else { if (GlobalData.CurrentSite == SiteType.Patreon) { if (doms[i].StartsWith(_preLink)) { ChangeHttp(doms[i], true); } else { var ss = HtmlToXamlConverter.ConvertHtmlToXaml(doms[i].Replace("\\n", "<br/>"), true); var fd = XamlReader.Load(new XmlTextReader(new StringReader(ss))) as FlowDocument; Paragraph pd = fd.Blocks.FirstBlock as Paragraph; List <Inline> tli = new List <Inline>(); while (null != pd) { try { foreach (var st in pd.Inlines) { if (st is Hyperlink) { (st as Hyperlink).Click += Hl_Patreon_Click; } tli.Add(st); } tli.Add(new LineBreak()); pd = pd.NextBlock as Paragraph; } catch (Exception ex) { Console.WriteLine(ex.Message); } } for (int l = 0; l < tli.Count; l++) { MainBody.Inlines.Add(tli[l]); } } } else { ChangeHttp(doms[i]); //var ts = doms[i].Split(new string[] { "\n" }, StringSplitOptions.None); //foreach (var dis in ts) //{ // var index = dis.IndexOf("http"); // if (index != -1) // { // var i2 = dis.IndexOf(' ', index); // flag = i2 != -1; // if (flag) // { // link = dis.Substring(index, i2 - index); // } // else // { // link = dis.Substring(index); // } // Hyperlink hl = new Hyperlink(new Run(link)) // { // CommandParameter = link // }; // hl.Click += Hl_Click; // if (index != 0) // { // MainBody.Inlines.Add(new Run(dis.Substring(0, index))); // } // MainBody.Inlines.Add(hl); // if (flag && i2 != dis.Length - 1) // { // MainBody.Inlines.Add(new Run(dis.Substring(i2))); // } // } // else // { // var rr = new Run(dis); // if (dis.Length > 0) // { // if (dis[0] == '$') // { // rr.FontSize = 30; // } // else if (dis.StartsWith(_preLink)) // { // rr.Foreground = Brushes.LightSkyBlue; // } // } // MainBody.Inlines.Add(rr); // } // MainBody.Inlines.Add(new LineBreak()); //} } } } if (!string.IsNullOrEmpty(bi.CoverPic)) { MainBody.Inlines.Add(new Run("------------------------------------------------------------------------------------------")); MainBody.Inlines.Add(new LineBreak()); Hyperlink hl = new Hyperlink(new Run(bi.CoverPicName)) { CommandParameter = new object[] { true, bi, -1 } }; hl.Click += AddDownload; Hyperlink hl1 = new Hyperlink(new Run(GlobalLanguage.Text_UseBrowser)) { CommandParameter = bi.CoverPic }; hl1.Click += Hl_Click; MainBody.Inlines.Add(hl); MainBody.Inlines.Add(" ("); MainBody.Inlines.Add(hl1); MainBody.Inlines.Add(")"); MainBody.Inlines.Add(new LineBreak()); } if (bi.ContentUrls.Count > 0) { MainBody.Inlines.Add(new Run("------------------------------------------------------------------------------------------")); MainBody.Inlines.Add(new LineBreak()); MainBody.Inlines.Add(new Run(GlobalLanguage.Text_FList) { FontSize = 25 }); MainBody.Inlines.Add(new LineBreak()); for (int i = 0; i < bi.ContentUrls.Count; i++) { Hyperlink hl = new Hyperlink(new Run(bi.FileNames[i])) { CommandParameter = new object[] { true, bi, i } }; hl.Click += AddDownload; Hyperlink hl1 = new Hyperlink(new Run(GlobalLanguage.Text_UseBrowser)) { CommandParameter = bi.ContentUrls[i] }; hl1.Click += Hl_Click; MainBody.Inlines.Add(hl); MainBody.Inlines.Add(" ("); MainBody.Inlines.Add(hl1); MainBody.Inlines.Add(")"); MainBody.Inlines.Add(new LineBreak()); } } if (bi.MediaUrls.Count > 0) { MainBody.Inlines.Add(new Run("------------------------------------------------------------------------------------------")); MainBody.Inlines.Add(new LineBreak()); MainBody.Inlines.Add(new Run(GlobalLanguage.Text_IList) { FontSize = 25 }); MainBody.Inlines.Add(new LineBreak()); for (int i = 0; i < bi.MediaUrls.Count; i++) { Hyperlink hl = new Hyperlink(new Run(bi.MediaNames[i])) { CommandParameter = new object[] { false, bi, i } }; hl.Click += AddDownload; MainBody.Inlines.Add(hl); Hyperlink hl1 = new Hyperlink(new Run(GlobalLanguage.Text_UseBrowser)) { CommandParameter = bi.MediaUrls[i] }; hl1.Click += Hl_Click; MainBody.Inlines.Add(hl); MainBody.Inlines.Add(" ("); MainBody.Inlines.Add(hl1); MainBody.Inlines.Add(")"); MainBody.Inlines.Add(new LineBreak()); } } }