示例#1
0
 public static void Append(this Paragraph paragraph, string value = "", Brush background = null, Brush foreground = null, bool bold = false, bool italic = false, bool underline = false)
 {
     Inline run = new Run(value);
     if (background != null) run.Background = background;
     if (foreground != null) run.Foreground = foreground;
     if (bold) run = new Bold(run);
     if (italic) run = new Italic(run);
     if (underline) run = new Underline(run);
     paragraph.Inlines.Add(run);
 }
        private Inline GetInlineWithStyling( string line, System.Drawing.FontStyle style )
        {
            Inline styledText = new Run( line );
            if ( style.HasFlag( System.Drawing.FontStyle.Bold ) )
                styledText = new Bold( styledText );

            if ( style.HasFlag( System.Drawing.FontStyle.Italic ) )
                styledText = new Italic( styledText );

            if ( style.HasFlag( System.Drawing.FontStyle.Underline ) )
                styledText = new Underline( styledText );

            return styledText;
        }
        public LiveTileNounPicture(Noun noun)
            : this()
        {
            TextBlock_Line1.Text =  Noun.GenderToString(noun.gender);

            TextBlock_Line3.Inlines.Clear();
            if (noun.genitivForm.Equals("") == false)
            {
                Run run = new Run();
                run.Text = noun.genitivForm + ", ";
                TextBlock_Line3.Inlines.Add(run);
            }
            if (noun.pluralForm.Equals("") == false)
            {
                if (noun.pluralForm.StartsWith("-.."))
                {
                    Underline underline = new Underline();
                    Run run = new Run();
                    run.Text = "..";
                    underline.Inlines.Add(run);

                    Run run2 = new Run();
                    run2.Text = noun.pluralForm.Substring(3);
                    TextBlock_Line3.Inlines.Add(underline);
                    TextBlock_Line3.Inlines.Add(run2);
                }
                else
                {
                    Run run = new Run();
                    run.Text = noun.pluralForm;
                    TextBlock_Line3.Inlines.Add(run);
                }
            }

            TextBlock_Line2.Text = noun.word;
            TextBlock_Line4.Text = noun.translation;

            UIHelper.ReduceFontSizeByWidth(TextBlock_Line2, 300);
            UIHelper.ReduceFontSizeByWidth(TextBlock_Line4, 300);
            UIHelper.SetTextBlockVerticalCenterOfCanvas(TextBlock_Line2);
            UIHelper.SetTextBlockVerticalCenterOfCanvas(TextBlock_Line4);
        }
        public OneSideNounCard(Noun noun) 
            : this()
        {
            TextBlock_Line1.Text = Noun.GenderToString(noun.gender);

            TextBlock_Line3.Inlines.Clear();
            if (noun.genitivForm.Equals("") == false)
            {
                Run run = new Run();
                run.Text = noun.genitivForm + ", ";
                TextBlock_Line3.Inlines.Add(run);
            }
            if (noun.pluralForm.Equals("") == false)
            {
                if (noun.pluralForm.StartsWith("-.."))
                {
                    Underline underline = new Underline();
                    Run run = new Run();
                    run.Text = "..";
                    underline.Inlines.Add(run);

                    Run run2 = new Run();
                    run2.Text = noun.pluralForm.Substring(3);
                    TextBlock_Line3.Inlines.Add(underline);
                    TextBlock_Line3.Inlines.Add(run2);
                }
                else
                {
                    Run run = new Run();
                    run.Text = noun.pluralForm;
                    TextBlock_Line3.Inlines.Add(run);
                }
            }

            TextBlock_Line2.Text = noun.word;
            nowword = noun.word;
            TextBlock_Line4.Text = noun.translation;

            UIHelper.ReduceFontSizeByWidth(TextBlock_Line2, 420);
            UIHelper.ReduceFontSizeByWidth(TextBlock_Line4, 420);
        }
示例#5
0
      // Recursively parses the given Html node into a corresponding Inline element
      private static Inline _parseHTMLNode(XNode node, HtmlBlock source) {
         if (node.NodeType == XmlNodeType.Text) {
            var text = ((XText)node).Value;
            text = text.ReplaceAll(_reWhitespace, " ");
            text = text.ReplaceAll(_reEncodedEntity, match => {
               var code = match.Groups[1].Value;
               if (code.At(0) == "#") {
                  return Char.ConvertFromUtf32(Int32.Parse(code.After(0)));
               } else if (_htmlEntities.ContainsKey(code)) {
                  return Char.ConvertFromUtf32(_htmlEntities[code]);
               } else {
                  throw new Exception(TEXT.HtmlBlock_UnrecognizedChar.Substitute(code));
               }
            });
            return new Run(text);
         }
         if (node.NodeType != XmlNodeType.Element) {
            return null;
         }

         var tag = (XElement)node;
         var name = tag.Name.LocalName.ToLower();
         Span outer = null;

         Brush  emphBrush = null;
         double fontSize  = 11;
         double paraBreak = 0;
         if (source != null) {
            emphBrush = source.EmphasizedForeground;
            fontSize = Double.IsNaN(source.FontSize) ? 11 : source.FontSize;
         }

         // hyperlink
         if (name == "a") {
            var link = new Hyperlink();
            var href = tag.Get<Uri>("href");
            if (href != null) link.NavigateUri = href;
            var trg = tag.Get("target");
            if (trg.NotEmpty()) link.TargetName = trg;
            outer = link;
         } 
         
         // bold
         else if (name == "b") {
            outer = new Bold();
         }

         // big
         else if (name == "big") {
            outer = new Span();
            outer.FontSize = fontSize * _fontFactors[4];
         }

         // line break
         else if (name == "br") {
            return new LineBreak();
         } 

         // code
         else if (name == "c" || name == "code") {
            outer = new Span();
            outer.FontFamily = new FontFamily("Courier New");
         }

         // code
         else if (name == "em") {
            outer = new Span();
            if (emphBrush != null) outer.Foreground = emphBrush;
         }

         // font style
         else if (name == "font") {
            outer = new Span();
            var face = tag.Get("face");
            if (face.NotEmpty()) outer.FontFamily = new FontFamily(face);
            var brush = tag.Get<Brush>("color", null);
            if (brush != null) outer.Foreground = brush;
            var size = tag.Get<int>("size", -1);
            if (size > 0) outer.FontSize = size;
         } 
         
         // header 1-6
         else if (name.Matches(_reHeaderTag)) {
            outer = new Bold();
            if (emphBrush != null) outer.Foreground = emphBrush;
            outer.FontSize = fontSize * _fontFactors[7-Int32.Parse(name.At(1))];
            paraBreak = 1;
         } 
         
         // italic
         else if (name == "i") {
            outer = new Italic();
         } 
         
         // image
         else if (name == "img") {
            outer = new Span();
            var uic = new InlineUIContainer();
            var img = new Image();
            var src = tag.GetImage("src");
            if (src != null) img.Source = src;
            var w = tag.Get<int>("width", -1);
            if (w >= 0) img.Width = w;
            var h = tag.Get<int>("height", -1);
            if (h >= 0) img.Height = h;
            uic.Child = img;
            outer.Inlines.Add(uic);
         } 
         
         // paragraph
         else if (name == "p") {
            outer = new Span();
            paraBreak = 4;
         }

         // small
         else if (name == "small") {
            outer = new Span();
            outer.FontSize = fontSize * _fontFactors[2];
         }

         // span
         else if (name == "span") {
            outer = new Span();
         } 
         
         // underline
         else if (name == "u") {
            outer = new Underline();
         } 
         
         // invalid tag
         else {
            throw new Exception(TEXT.HtmlBlock_UnrecognizedTag.Substitute(tag.Name.LocalName));
         }

         var tip = tag.GetImage("title");
         if (tip != null) {
            outer.ToolTip = tip;
         }

         foreach (var child in tag.Nodes()) {
            var inner = _parseHTMLNode(child, source);
            if (inner != null) outer.Inlines.Add(inner);
         }
         if (paraBreak == 0) return outer;

         var para = new Span();
         para.Inlines.Add(outer);
         para.Inlines.Add(new LineBreak());
         var blankline = new Span();
         blankline.FontSize = paraBreak;
         para.Inlines.Add(blankline);
         para.Inlines.Add(new LineBreak());
         return para;
      }
示例#6
0
        public void AddMsgToOutputBox(IMMessage imMessage, string senderName, AddMsgToOutputBoxCallBackHandler callBack)
        {
            this.CheckMsgPiece();
            InputBox box = this;
            MessagePack messagePack = imMessage.MessagePack;
            if (messagePack != null)
            {
                if (messagePack.NeedShowHeader && (imMessage.Sender == null))
                {
                    messagePack.NeedShowHeader = false;
                }
                if (messagePack.NeedShowHeader && string.IsNullOrEmpty(senderName))
                {
                    senderName = imMessage.SenderName;
                    if (string.IsNullOrEmpty(senderName))
                    {
                        senderName = imMessage.Sender.NickName;
                    }
                }
                uint elemCount = messagePack.GetElemCount();
                Section newItem = new Section();
                Block lastBlock = box.Document.Blocks.LastBlock;
                if ((lastBlock != null) && (string.Compare(lastBlock.Tag as string, "LastTag") != 0))
                {
                    lastBlock = null;
                }
                if (lastBlock == null)
                {
                    Paragraph paragraph = new Paragraph
                    {
                        Tag = "LastTag",
                        Margin = new Thickness(0.0)
                    };
                    lastBlock = paragraph;
                    box.Document.Blocks.Add(lastBlock);
                }
                if (messagePack.NeedShowHeader)
                {
                    if ((imMessage.Sender != null) && (imMessage.Sender.Uin == Util_Buddy.GetCurrentBuddy().Uin))
                    {
                        newItem.Tag = "me";
                    }
                    else
                    {
                        newItem.Tag = "other";
                    }
                }
                else
                {
                    newItem.Tag = "info";
                }
                box.Document.Blocks.InsertBefore(lastBlock, newItem);
                Paragraph item = new Paragraph();
                if (messagePack.NeedShowHeader)
                {
                    string str;
                    Paragraph paragraph3 = new Paragraph
                    {
                        Foreground = new SolidColorBrush((imMessage.Sender.Uin == Util_Buddy.GetCurrentBuddy().Uin) ? this._selfColor : this._oppColor)
                    };
                    if (this.IsMsgRecord)
                    {
                        str = senderName + "  " + imMessage.DateTime.ToLocalTime().ToString();
                    }
                    else
                    {
                        str = senderName + "  " + imMessage.DateTime.ToLocalTime().ToLongTimeString();
                        item.Margin = new Thickness(13.0, 0.0, 0.0, 0.0);
                    }
                    paragraph3.Inlines.Add(str);
                    newItem.Blocks.Add(paragraph3);
                }
                SetDateTime(newItem, imMessage.DateTime);
                Paragraph paragraph4 = new Paragraph
                {
                    Margin = new Thickness(13.0, 0.0, 0.0, 0.0)
                };
                string fontName = messagePack.Header.FontName;
                if ((string.IsNullOrEmpty(fontName) || (fontName == "宋体")) || (((fontName == "新宋体") || (fontName == "仿宋")) || (fontName == "黑体")))
                {
                    fontName = "Microsoft YaHei";
                }
                if (messagePack.Header.FontSize == 0)
                {
                    messagePack.Header.FontSize = 9;
                }
                item.FontFamily = new FontFamily(fontName);
                item.FontSize = messagePack.Header.FontSize + 3;
                item.Foreground = new SolidColorBrush(messagePack.Header.FontColor);
                paragraph4.FontFamily = new FontFamily(messagePack.Header.FontName);
                paragraph4.FontSize = messagePack.Header.FontSize + 3;
                paragraph4.Foreground = new SolidColorBrush(messagePack.Header.FontColor);
                Dictionary<string, bool> imagelist = new Dictionary<string, bool>();
                Paragraph paragraph5 = item;
                bool flag = false;
                for (uint i = 0; i < elemCount; i++)
                {
                    ImageElement element4;
                    string path;
                    ImageEx ex2;
                    MessageElement elem = messagePack.GetElem(i);
                    switch (elem.Category)
                    {
                        case MsgPackCat.ELEMTYPE_TEXT:
                            {
                                Guid guid;
                                Guid guid2;
                                TextElement element2 = (TextElement)elem;
                                string text = element2.GetText();
                                if (!flag && element2.NeedIndent)
                                {
                                    Span lastInline = item.Inlines.LastInline as Span;
                                    if (lastInline != null)
                                    {
                                        Run run = lastInline.Inlines.LastInline as Run;
                                        if (run != null)
                                        {
                                            run.Text = run.Text.Replace("\r", "").Replace("\n", "");
                                        }
                                    }
                                    paragraph5 = paragraph4;
                                }
                                string url = element2.GetUrl(out guid, out guid2);
                                Span span2 = new Span();
                                Span span3 = span2;
                                paragraph5.Inlines.Add(span3);
                                if ((messagePack.Header.FontEffect & 2) != 0)
                                {
                                    span2.FontStyle = FontStyles.Italic;
                                }
                                if ((messagePack.Header.FontEffect & 1) != 0)
                                {
                                    span2.FontWeight = FontWeights.Bold;
                                }
                                if (string.IsNullOrEmpty(url))
                                {
                                    if ((messagePack.Header.FontEffect & 4) != 0)
                                    {
                                        Underline underline = new Underline();
                                        span2.Inlines.Add(underline);
                                        span2 = underline;
                                    }
                                    span2.Inlines.Add(text);
                                }
                                else
                                {
                                    ImageHyperlink hyperlink = new ImageHyperlink
                                    {
                                        Guid = guid,
                                        SoureUrl = url
                                    };
                                    span2.Inlines.Add(hyperlink);
                                    span2 = hyperlink;
                                    hyperlink.AddText(text);
                                    this.OnImageHyperLinkAdd(imMessage, hyperlink);
                                }
                                continue;
                            }
                        case MsgPackCat.ELEMTYPE_SYSFACE:
                            {
                                SysFaceElement element = (SysFaceElement)elem;
                                ImageEx uiElement = ReplaceControls.CreateImageExWithId(element.FileName, element.Index.ToString());
                                uiElement.Width = element.FaceWidth;
                                uiElement.Height = element.FaceHeight;
                                paragraph5.Inlines.Add(uiElement);
                                if (callBack != null)
                                {
                                    callBack(imMessage, element);
                                }
                                continue;
                            }
                        case MsgPackCat.ELEMTYPE_IMAGE:
                        case MsgPackCat.ELEMTYPE_OFFLINEPIC:
                            element4 = (ImageElement)elem;
                            path = element4.Path;
                            if (string.IsNullOrEmpty(path))
                            {
                                continue;
                            }
                            ex2 = new ImageEx
                            {
                                HorizontalAlignment = HorizontalAlignment.Left,
                                VerticalAlignment = VerticalAlignment.Top,
                                Stretch = Stretch.None,
                                SnapsToDevicePixels = true,
                                Tag = element4
                            };
                            path = path.ToLower();
                            if (!CheckFileExists(imagelist, path))
                            {
                                break;
                            }
                            ex2.Source = path;
                            goto Label_0710;

                        case MsgPackCat.ELEMTYPE_FILE:
                            {
                                FileElement element5 = (FileElement)elem;
                                string str7 = Helper_Icon.MakeSysIconFileByFileName(element5.Path);
                                string fileSize = element5.GetFileSize();
                                string fileName = element5.GetFileName();
                                if (!string.IsNullOrEmpty(str7))
                                {
                                    ImageEx ex3 = new ImageEx
                                    {
                                        HorizontalAlignment = HorizontalAlignment.Left,
                                        VerticalAlignment = VerticalAlignment.Top,
                                        Stretch = Stretch.Uniform,
                                        SnapsToDevicePixels = true,
                                        Width = 32.0,
                                        Height = 32.0
                                    };
                                    if (!string.IsNullOrEmpty(element5.Tip))
                                    {
                                        ex3.ToolTip = element5.Tip;
                                    }
                                    ex3.Source = str7;
                                    StackPanel panel = new StackPanel
                                    {
                                        Margin = new Thickness(0.0, 2.0, 0.0, 2.0),
                                        Orientation = Orientation.Horizontal
                                    };
                                    panel.Children.Add(ex3);
                                    TextBlock block2 = new TextBlock(new Run(fileName + "\n" + fileSize))
                                    {
                                        Margin = new Thickness(0.0, 4.0, 0.0, 0.0)
                                    };
                                    panel.Children.Add(block2);
                                    paragraph5.Inlines.Add(panel);
                                }
                                continue;
                            }
                        default:
                            goto Label_087B;
                    }
                    if (this.IsMsgRecord)
                    {
                        ex2.Source = CoreMessenger.Instance.GetAppPath(KernelWrapper.APP_PATH_TYPE.APP_PATH_DATA) + "errorBmp.gif";
                    }
                    else if (MsgPackCat.ELEMTYPE_IMAGE == elem.Category)
                    {
                        TXLog.TXLogImage(string.Concat(new object[] { "收到图片文件需要下载:", element4.Id, "  ", path }));
                        ex2.Source = CoreMessenger.Instance.GetAppPath(KernelWrapper.APP_PATH_TYPE.APP_PATH_DATA) + "sendingBmp.gif";
                        this.AddToImagesDownloadingList(element4.Id, ex2);
                    }
                    else if (MsgPackCat.ELEMTYPE_OFFLINEPIC == elem.Category)
                    {
                        TXLog.TXLogImage(string.Concat(new object[] { "收到离线图片文件需要下载:", element4.Id, "  ", path }));
                        ex2.IsEnabledClick = true;
                        ex2.Source = CoreMessenger.Instance.GetAppPath(KernelWrapper.APP_PATH_TYPE.APP_PATH_DATA) + "OfflinepicManualGet.png";
                        ex2.ToolTip = "点击获取图片";
                        ex2.Cursor = Cursors.Hand;
                    }
                Label_0710:
                    paragraph5.Inlines.Add(ex2);
                    continue;
                Label_087B:
                    TXLog.TXLog3("Msg", "AIO 未处理的消息类型, ");
                }
                if (item.Inlines.Count > 0)
                {
                    newItem.Blocks.Add(item);
                }
                if (paragraph4.Inlines.Count > 0)
                {
                    newItem.Blocks.Add(paragraph4);
                }
                box.ScrollToEnd();
            }
        }
        private static Inline GetInline(FrameworkElement element, InlineDescription description)
        {
            Style style = null;
            if (!string.IsNullOrEmpty(description.StyleName))
            {
                style = element.FindResource(description.StyleName) as Style;
                if (style == null)
                    throw new InvalidOperationException("The style '" + description.StyleName + "' cannot be found");
            }

            Inline inline = null;
            switch (description.Type)
            {
                case InlineType.Run:
                    var run = new Run(description.Text);
                    inline = run;
                    break;

                case InlineType.LineBreak:
                    var lineBreak = new LineBreak();
                    inline = lineBreak;
                    break;

                case InlineType.Span:
                    var span = new Span();
                    inline = span;
                    break;

                case InlineType.Bold:
                    var bold = new Bold();
                    inline = bold;
                    break;

                case InlineType.Italic:
                    var italic = new Italic();
                    inline = italic;
                    break;

                case InlineType.Hyperlink:
                    var hyperlink = new Hyperlink();
                    inline = hyperlink;
                    break;

                case InlineType.Underline:
                    var underline = new Underline();
                    inline = underline;
                    break;
            }

            if (inline != null)
            {
                var span = inline as Span;
                if (span != null)
                {
                    var childInlines =
                        description.Inlines.Select(inlineDescription => GetInline(element, inlineDescription))
                            .Where(childInline => childInline != null)
                            .ToList();

                    span.Inlines.AddRange(childInlines);
                }

                if (style != null)
                    inline.Style = style;
            }

            return inline;
        }
示例#8
0
        /// <summary>
        /// Parses an html string to an InlineCollection. The opening tags
        /// and closing tags MUST match, otherwise the result is undefined.
        /// </summary>
        /// <param name="html"></param>
        /// <remarks>
        /// The following HTML tags are supported:
        ///   a -> Hyperlink
        ///   b -> Bold
        ///   i -> Italic
        ///   u -> Underline
        ///   br -> LineBreak (close tag optional)
        ///   (plain text) -> Run
        /// 
        /// The following WPF elements that are valid child elements of Span
        /// are not supported by this method:
        ///   Figure, Floater, InlineUIContainer.
        /// </remarks>
        /// <returns></returns>
        private static Inline ConvertHtmlToInlines(string html)
        {
            if (html == null)
                throw new ArgumentNullException("html");

            // Maintain a stack of the top Span element. For example,
            // <b><a href="somewhere">click me</a> if you <i>want</i>.</b>
            // would push an element to the stack for each open tag, and
            // pop an element from the stack for each close tag.
            Stack<Span> elementStack = new Stack<Span>();
            Span top = new Span();
            elementStack.Push(top);

            for (int index = 0; index < html.Length; )
            {
                int k1 = html.IndexOf('<', index);
                if (k1 == -1) // all text
                {
                    top.Inlines.Add(new Run(html.Substring(index)));
                    break;
                }
                if (k1 > index) // at least some text
                {
                    top.Inlines.Add(new Run(html.Substring(index, k1 - index)));
                    index = k1;
                }

                // Now 'index' points to '<'. Search for '>'.
                int k2 = html.IndexOf('>', index + 1);
                if (k2 == -1) // '<' without '>'
                {
                    top.Inlines.Add(new Run(html.Substring(index)));
                    break;
                }
                
                string tagString = html.Substring(k1 + 1, k2 - k1 - 1);
                HtmlElement tag = HtmlElement.Parse(tagString);
                string tagName = (tag != null) ? tag.Name.ToLowerInvariant() : null;

                if (tagName == null) // parse failed; output as is
                {
                    top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1)));
                }
                else if (tagName != "" && tagName[0] == '/') // close tag
                {
                    if (tagName == "/a" && top is Hyperlink ||
                        tagName == "/b" && top is Bold ||
                        tagName == "/i" && top is Italic ||
                        tagName == "/u" && top is Underline ||
                        tagName == "/span" && top is Span) // TBD: might pop top element
                    {
                        elementStack.Pop();
                        top = elementStack.Peek();
                    }
                    else
                    {
                        // unmatched close tag; output as is.
                        top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1)));
                    }
                }
                else // open tag or open-close tag (e.g. <br/>)
                {
                    Inline element = null;
                    switch (tagName)
                    {
                        case "span":
                            element = new Span();
                            break;
                        case "a":
                            {
                                Hyperlink hyperlink = new Hyperlink();
                                if (tag.Attributes != null)
                                {
                                    foreach (HtmlAttribute attr in tag.Attributes)
                                    {
                                        if (attr.Name == "href")
                                            hyperlink.NavigateUri = new Uri(attr.Value, UriKind.RelativeOrAbsolute);
                                    }
                                }
                                element = hyperlink;
                            }
                            break;
                        case "b":
                            element = new Bold();
                            break;
                        case "i":
                            element = new Italic();
                            break;
                        case "u":
                            element = new Underline();
                            break;
                        case "br":
                            break;
                    }

                    if (element != null) // supported element
                    {
                        // Check global attributes.
                        if (tag.Attributes != null)
                        {
                            foreach (HtmlAttribute attr in tag.Attributes)
                            {
                                if (attr.Name == "title")
                                {
                                    ToolTipService.SetShowDuration(element, 60000);
                                    element.ToolTip = attr.Value;
                                }
                            }
                        }

                        top.Inlines.Add(element);
                        if (element is Span &&   // not br
                            html[k2 - 1] != '/') // not self-closed tag
                        {
                            elementStack.Push((Span)element);
                            top = (Span)element;
                        }
                    }
                    else // unsupported element, treat as text
                    {
                        top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1)));
                    }
                }

                index = k2 + 1;
            }

            // Return the root element. Note that some open tags may not be
            // closed, but we ignore that.
            while (elementStack.Count > 0)
            {
                top = elementStack.Pop();
            }
            return top; // .Inlines;
        }
        private static Span CreateSpan(InlineType inlineType, string param)
        {
            Span span = null;

            switch (inlineType)
            {
                case InlineType.Hyperlink:
                    Hyperlink link = new Hyperlink();

                    Uri uri;
                    if (Uri.TryCreate(param, UriKind.Absolute, out uri))
                    {
                        link.NavigateUri = uri;
                    }

                    span = link;
                    break;
                case InlineType.Bold:
                    span = new Bold();
                    break;
                case InlineType.Italic:
                    span = new Italic();
                    break;
                case InlineType.Underline:
                    span = new Underline();
                    break;
                default:
                    span = new Span();
                    break;
            }

            return span;
        }
示例#10
0
 public Inline StringToRun(String s, Brush b)
 {
     Inline ret = null;
     String strUrlRegex = "(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))";
     Regex reg = new Regex(strUrlRegex);
     s = s.Trim();
     //b = Brushes.Black;
     Inline r = new Run(s);
     if (reg.IsMatch(s))
     {
         b = Brushes.LightBlue;
         Hyperlink h = new Hyperlink(r);
         h.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(h_RequestNavigate);
         try
         {
             h.NavigateUri = new Uri(s);
         }
         catch (UriFormatException)
         {
             s = "http://" + s;
             try
             {
                 h.NavigateUri = new Uri(s);
             }
             catch (Exception)
             {
                 r.Foreground = b;
                 System.Windows.Documents.Underline ul = new Underline(r);
             }
         }
         ret = h;
     }
     else
     {
         if (s.Equals(Program.lobbyClient.Me.DisplayName))
         {
             b = Brushes.Blue;
             ret = new Bold(r);
         }
         else
         {
             Boolean fUser = false;
             foreach (User u in listBox1.Items)
             {
                 if (u.DisplayName == s)
                 {
                     b = Brushes.LightGreen;
                     ret = new Bold(r);
                     ret.ToolTip = "Click to whisper";
                     r.Cursor = Cursors.Hand;
                     r.Background = Brushes.White;
                     r.MouseEnter += delegate(object sender, MouseEventArgs e)
                     {
                         r.Background = new RadialGradientBrush(Colors.DarkGray, Colors.WhiteSmoke);
                     };
                     r.MouseLeave += delegate(object sender, MouseEventArgs e)
                     {
                         r.Background = Brushes.White;
                     };
                     fUser = true;
                     break;
                 }
             }
             if (!fUser)
             {
                 ret = new Run(s);
             }
         }
     }
     ret.Foreground = b;
     return ret;
 }
示例#11
0
        /// <summary>
        /// The bound HtmlDocument changed. Map the HTML nodes into XAML nodes and build the corresponding
        /// RichTextBox for display.
        /// </summary>
        private static void FormattedTextChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            // TODO, Split up long boxes so that they are under height 2000px
            RichTextBox textBlock = sender as RichTextBox;
            textBlock.Blocks.Clear();

            HtmlDocument doc = e.NewValue as HtmlDocument;
            if (doc == null)
            {
                return;
            }

            Paragraph para = new Paragraph();
            foreach (var node in doc.DocumentNode.ChildNodes)
            {
                HtmlNode _node = node;
                // Hack to allow nested font tag
                if (_node.Name == "font" && _node.FirstChild != null) _node = node.FirstChild;
                // Hack to allow strange quotes (nested in a span class quote tag)
                else if (_node.Name == "span" && _node.Attributes.Contains("class") &&
                    _node.Attributes["class"].Value == "quote" && _node.HasChildNodes
                    && _node.FirstChild.Name == "a" && _node.FirstChild.Attributes.Contains("class") &&
                    _node.FirstChild.Attributes["class"].Value == "quotelink" &&
                    _node.FirstChild.Attributes.Contains("href")) _node = _node.FirstChild;

                if (_node.Name == "br") para.Inlines.Add(new LineBreak());
                // Regular quote
                else if (_node.Name == "a" && _node.Attributes.Contains("class") &&
                    _node.Attributes["class"].Value == "quotelink" &&
                    _node.Attributes.Contains("href"))
                {
                    Match m = r.Match(_node.Attributes["href"].Value);
                    // Thread quote
                    if (m.Success)
                    {
                        Hyperlink h = new Hyperlink();
                        h.Click += (hsender, he) =>
                        {
                            if (textBlock.DataContext is PostViewModel)
                            {
                                // Because this click is *not* a routed event, we can't cancel it or
                                // mark it as handled and it will actually bubble down to the child post
                                // grid and hit that tap event too. To work around this we set the rootframe
                                // hit test property as a sentinel value to signal that tap handler to ignore
                                // the invocation.
                                App.IsPostTapAllowed = false;
                                PostViewModel pvm = (PostViewModel)textBlock.DataContext;
                                pvm.QuoteLinkTapped(m.Groups[2].Value, m.Groups[3].Value, ulong.Parse(m.Groups[4].Value));

                                // We clear this sentinel property on the dispatcher, since the routed tap events actually get queued on
                                // the dispatcher and don't happen until this current function returns.
                                Deployment.Current.Dispatcher.BeginInvoke(() => App.IsPostTapAllowed = true);
                            }
                        };
                        h.Inlines.Add(new Run()
                        {
                            Foreground = App.Current.Resources["LinkBrush"] as SolidColorBrush,
                            Text = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ",")
                        });
                        para.Inlines.Add(h);
                    }
                    else
                    {

                        Match m3 = r3.Match(_node.Attributes["href"].Value);
                        if (m3.Success)
                        {
                            Hyperlink h = new Hyperlink();
                            h.Click += (hsender, he) =>
                            {
                                if (textBlock.DataContext is PostViewModel)
                                {
                                    App.IsPostTapAllowed = false;
                                    (textBlock.DataContext as PostViewModel).BoardLinkTapped(m3.Groups[1].Value + m3.Groups[2].Value);
                                    Deployment.Current.Dispatcher.BeginInvoke(() => App.IsPostTapAllowed = true);
                                }
                            };
                            h.Inlines.Add(new Run()
                            {
                                Foreground = App.Current.Resources["LinkBrush"] as SolidColorBrush,
                                Text = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ",")
                            });
                            para.Inlines.Add(h);
                        }
                        else
                        {
                            Match m2 = r2.Match(_node.Attributes["href"].Value);
                            // Text board quote?
                            if (m2.Success)
                            {
                                para.Inlines.Add(WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ","));
                            }
                            else
                            {
                                //Debug.WriteLine(_node.OuterHtml);
                                para.Inlines.Add(WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ","));
                            }
                        }
                    }
                }
                // Dead Quote
                else if (_node.Name == "span" &&
                    _node.Attributes.Contains("class") &&
                    _node.Attributes["class"].Value == "quote deadlink")
                {
                    para.Inlines.Add(new Run()
                    {
                        Foreground = App.Current.Resources["GreentextBrush"] as SolidColorBrush,
                        Text = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ",")
                    });
                }
                // Greentext
                else if (_node.Name == "span" && _node.Attributes.Contains("class") &&
                    _node.Attributes["class"].Value == "quote")
                {
                    para.Inlines.Add(new Run()
                    {
                        Foreground = App.Current.Resources["GreentextBrush"] as SolidColorBrush,
                        Text = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ",")
                    });
                }
                // Dead Quote 2#
                else if (_node.Name == "span" && _node.Attributes.Contains("class") && _node.Attributes["class"].Value == "quote deadlink")
                {
                    para.Inlines.Add(new Run()
                    {
                        Foreground = App.Current.Resources["GreentextBrush"] as SolidColorBrush,
                        Text = WebUtility.HtmlDecode(_node.ChildNodes[0].InnerText).Replace("&#039;", "'").Replace("&#44;", ",")
                    });
                }
                // Banned text
                else if ((_node.Name == "b" || _node.Name == "strong") && _node.Attributes.Contains("style") &&
                    _node.Attributes["style"].Value.Replace(" ", "") == "color:red;")
                {
                    para.Inlines.Add(new Run()
                    {
                        Foreground = App.Current.Resources["BannedBrush"] as SolidColorBrush,
                        Text = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ",")
                    });
                }
                // Spoiler
                else if (_node.Name == "s")
                {
                    Hyperlink h = new Hyperlink()
                    {
                        TextDecorations = null
                    };
                    int len = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ",").Length;
                    // To simulate spoiler display, we just put the unicode wide block symbol over and over in a spoiler color,
                    // since we can't actually highlight a region of the text or obscure it normally.
                    Run r = new Run()
                    {
                        Foreground = App.Current.Resources["SpoilerBrush"] as SolidColorBrush,
                        Text = new String('\u2588', len),
                        FontSize = CriticalSettingsManager.Current.TextSize
                    };
                    bool isClicked = false;
                    h.Click += (hsender, he) =>
                    {
                        if (isClicked) return;

                        isClicked = true;
                        App.IsPostTapAllowed = false;
                        r.Text = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ",");
                        r.FontSize = CriticalSettingsManager.Current.TextSize;
                        h.TextDecorations = null;
                        Deployment.Current.Dispatcher.BeginInvoke(() => App.IsPostTapAllowed = true);
                    };
                    h.Inlines.Add(r);
                    para.Inlines.Add(h);
                }
                //Hyperlink
                else if (_node.Name == "a" && _node.Attributes.Contains("href"))
                {
                    Hyperlink h = new Hyperlink() { NavigateUri = new Uri(_node.Attributes["href"].Value), TargetName = "_blank" };
                    h.Click += (hsender, he) =>
                    {
                        App.IsPostTapAllowed = false;
                        Deployment.Current.Dispatcher.BeginInvoke(() => App.IsPostTapAllowed = true);
                    };
                    h.Inlines.Add(new Run()
                    {
                        Foreground = App.Current.Resources["LinkBrush"] as SolidColorBrush,
                        Text = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ",")
                    });
                    para.Inlines.Add(h);
                }
                // Bold
                else if (_node.Name == "b" || _node.Name == "strong")
                {
                    Bold b = new Bold();
                    b.Inlines.Add(WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ","));
                    para.Inlines.Add(b);
                }
                // Underline
                else if (_node.Name == "u")
                {
                    Underline u = new Underline();
                    u.Inlines.Add(WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ","));
                    para.Inlines.Add(u);

                }
                else if (_node.Name == "small")
                {
                    para.Inlines.Add(new Run()
                    {
                        Text = WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ","),
                        FontSize = CriticalSettingsManager.Current.TextSize - 3
                    });
                }
                // Regular text
                else if (_node.Name == "#text")
                {
                    // para.Inlines.Add(WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ","));
                    List<Inline> inlines = MarkupLinks(WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ","));
                    foreach (Inline inline in inlines) para.Inlines.Add(inline);
                }
                else
                {
                    //Debug.WriteLine(_node.OuterHtml);
                    para.Inlines.Add(WebUtility.HtmlDecode(_node.InnerText).Replace("&#039;", "'").Replace("&#44;", ","));
                }
            }

            textBlock.Blocks.Add(para);
        }
        public TwoSideNounCard(Noun noun, bool isWordInFront)
            : this()
        {
            if (isWordInFront)
            {
                TextBlock_FrontLine1.Text = noun.word;
                TextBlock_BackLine2.Text = noun.translation;
            }
            else
            {
                TextBlock_FrontLine1.Text = noun.translation;
                TextBlock_BackLine2.Text = noun.word;
            }
            nowword = noun.word;
            switch (noun.gender)
            {
                case WordGender.Masculine:
                    TextBlock_BackLine1.Text = "der";
                    break;
                case WordGender.Feminine:
                    TextBlock_BackLine1.Text = "die";
                    break;
                case WordGender.Neuter:
                    TextBlock_BackLine1.Text = "das";
                    break;
                case WordGender.MasculineOrNeuter:
                    TextBlock_BackLine1.Text = "der/das";
                    break;
                case WordGender.None:
                    TextBlock_BackLine1.Text = "";
                    break;
            }

            TextBlock_BackLine3.Inlines.Clear();
            if (noun.genitivForm.Equals("") == false)
            {
                Run run = new Run();
                run.Text = noun.genitivForm + ", ";
                TextBlock_BackLine3.Inlines.Add(run);
            }
            if (noun.pluralForm.Equals("") == false)
            {
                if (noun.pluralForm.StartsWith("-.."))
                {
                    Underline underline = new Underline();
                    Run run = new Run();
                    run.Text = "..";
                    underline.Inlines.Add(run);

                    Run run2 = new Run();
                    run2.Text = noun.pluralForm.Substring(3);
                    TextBlock_BackLine3.Inlines.Add(underline);
                    TextBlock_BackLine3.Inlines.Add(run2);
                }
                else
                {
                    Run run = new Run();
                    run.Text = noun.pluralForm;
                    TextBlock_BackLine3.Inlines.Add(run);
                }
            }

            UIHelper.ReduceFontSizeByWidth(TextBlock_FrontLine1, 420);
            UIHelper.ReduceFontSizeByWidth(TextBlock_BackLine2, 420);
        }
示例#13
0
        /// <summary>
        /// А теперь большой кусок говнокода (:
        /// Требуется это все перевести в XAML
        /// Так же возможно после хамл вынести в отдельный файл чтобы можно было редактировать из вне и загружать динамически :S
        /// </summary>
        private void GenerateDocument(string fullName, string passort, DateTime dateStart, DateTime dateEnd)
        {
            var p1 = new Paragraph();

            var fioLine = new Underline();
            fioLine.Inlines.Add(fullName);
            p1.Inlines.Add(fioLine);

            if (!string.IsNullOrEmpty(passort))
            {
                p1.Inlines.Add(" (паспортные данные ");
                var passportLine = new Underline();
                passportLine.Inlines.Add(passort);
                p1.Inlines.Add(passportLine);
                p1.Inlines.Add(")");
            }
            p1.Inlines.Add(" даллее по тексту \"Арендатор\" принимает в почасовую аренду оборудование, перечень которого содержится в приложение №1 к настоящему Договору, и декорации фотостудии.");

            var p2 = new Paragraph();
            var point1 = new Bold();
            point1.Inlines.Add("1. ");

            p2.Inlines.Add(point1);
            p2.Inlines.Add(" Время аренды Фотостудии: ");
            
            var day = new Underline();
            day.Inlines.Add(string.Format("\"{0}\" ", dateStart.Day));

            p2.Inlines.Add(day);

            var mount = new Underline();
            mount.Inlines.Add(GetMounth(dateStart.Month));

            p2.Inlines.Add(mount);
            p2.Inlines.Add(string.Format(" {0} г. с ", dateStart.Year));

            var hourStart = new Underline();
            hourStart.Inlines.Add(dateStart.Hour.ToString("00"));

            var minuteStart = new Underline();
            minuteStart.Inlines.Add(dateStart.Minute.ToString("00"));

            var hourEnd = new Underline();
            hourEnd.Inlines.Add(dateEnd.Hour.ToString("00"));

            var minuteEnd = new Underline();
            minuteEnd.Inlines.Add(dateEnd.Minute.ToString("00"));

            p2.Inlines.Add(hourStart); p2.Inlines.Add(" часов "); p2.Inlines.Add(minuteStart); p2.Inlines.Add(" минут до "); p2.Inlines.Add(hourEnd); p2.Inlines.Add(" часов "); p2.Inlines.Add(minuteEnd); p2.Inlines.Add(" минут.");

            p2.Inlines.Add(
                @" В случае если Арендатор закончил работу в Фотостудии ранее, чем оформлено в настоящем Договоре,
оплачивается заказанное время аренды. Также Арендатор оплачивает время, проведенное в Фотостудии свыше указанного в настоящем Договоре по факту завершения работы. Также в случае, если арендатор явился позже забронированного времени, то он оплачивает полностью забронированное время.
");

            var p3 = new Paragraph();
            var point2 = new Bold();
            point2.Inlines.Add("2. Арендатор обязан:");

            p3.Inlines.Add(point2);

            var p4 = new Paragraph();
            p4.Inlines.Add(string.Format(@"{0} использовать Фотостудию и оборудование исключительно по прямому назначению, и только во время, указанное в п. 1. настоящего Договора;", Helpers.RtbHelper.AllBullets["Disc"]));

            var p5 = new Paragraph();
            p5.Inlines.Add(
                string.Format(
                    @"{0} содержать арендуемую Фотостудию и оборудование в порядке, предусмотренном санитарными и противопожарными нормами и правилами;",
                    Helpers.RtbHelper.AllBullets["Disc"]));

            var p6 = new Paragraph();
            p6.Inlines.Add("• вносить почасовую арендую плату в установленные договором сроки;");

            var p7 = new Paragraph();
            p7.Inlines.Add("• нести ответственность за исправность оборудования и декораций во время аренды Фотостудии, а в случае порчи вышеуказанного оборудования и декораций возмещать его стоимость в полном объеме в течение одного календарного дня;");

            var p8 = new Paragraph();
            p8.Inlines.Add("• не распивать алкогольные напитки и курить в съемочных залах");

            var p9 = new Paragraph();
            var point3 = new Bold();
            point3.Inlines.Add("3. Порядок расчетов");
          
            p9.Inlines.Add(point3);

            var p10 = new Paragraph();
            var point3_1 = new Bold();
            point3_1.Inlines.Add("3.1 ");

            p10.Inlines.Add(point3_1);
//            p10.Inlines.Add(
//                string.Format(
//                    @"Арендная плата составляет в зале 120кв м 800 (восемьсот) рублей за час круглосуточно по будням, 900 (девятьсот) рублей по выходным круглосуточно, съемочный день круглосуточно будни 7000 руб/смена 10 часов, съемочный день круглосуточно выходные 8000 руб/смена 10 часов, использование циклорамы 500 руб за все время аренды. В зале 85 кв м Будни круглосуточно 700 руб/час, Выходные круглосуточно 800 руб/час, Использование циклорамы 500 руб за все время аренды, Съемочный день круглосуточно будни 6000 руб/смена 10 часов, Съемочный день круглосуточно выходные 7000 руб/смена 10 часов"));

            p10.Inlines.Add(GetBlock3_1());

            var p11 = new Paragraph();
            var point3_2 = new Bold();
            point3_2.Inlines.Add("3.2 ");
            
            p11.Inlines.Add(point3_2);
            p11.Inlines.Add(string.Format("На момент подписания настоящего Договора Арендатор осмотрел помещение и оборудование."));
            
            p11.Inlines.Add(new LineBreak());
            p11.Inlines.Add(new LineBreak());

            var p12 = new Paragraph();
            var point4 = new Bold();
            point4.Inlines.Add("Приложение №1");

            p12.Inlines.Add(point4);

            var p13 = new Paragraph();
            p13.Inlines.Add("Перечень оборудования");

            word.Blocks.Add(p1);
            word.Blocks.Add(p2);
            word.Blocks.Add(p3);
            word.Blocks.Add(p4);
            word.Blocks.Add(p5);
            word.Blocks.Add(p6);
            word.Blocks.Add(p7);
            word.Blocks.Add(p8);
            word.Blocks.Add(p9);
            word.Blocks.Add(p10);
            word.Blocks.Add(p11);
            word.Blocks.Add(p12);
            word.Blocks.Add(p13);

            #region Перчень в приложении

            var listItem1 = new Bold();
            listItem1.Inlines.Add("1) ");

            var p14 = new Paragraph();
            p14.Inlines.Add(listItem1);
            p14.Inlines.Add("4 моноблока Bowens 500 R");

            word.Blocks.Add(p14);

            var listItem2 = new Bold();
            listItem2.Inlines.Add("2) ");

            var p15 = new Paragraph();
            p15.Inlines.Add(listItem2);
            p15.Inlines.Add("Рефлектор  6’’ 2 шт");

            word.Blocks.Add(p15);

            var listItem3 = new Bold();
            listItem3.Inlines.Add("3) ");

            var p16 = new Paragraph();
            p16.Inlines.Add(listItem3);
            p16.Inlines.Add("Октабокс 150 см");

            word.Blocks.Add(p16);

            var listItem4 = new Bold();
            listItem4.Inlines.Add("4) ");

            var p17 = new Paragraph();
            p17.Inlines.Add(listItem4);
            p17.Inlines.Add("Софтбокс 100*120 см");

            word.Blocks.Add(p17);

            var listItem5 = new Bold();
            listItem5.Inlines.Add("5) ");

            var p18 = new Paragraph();
            p18.Inlines.Add(listItem5);
            p18.Inlines.Add("Светоотражатель Raylab");

            word.Blocks.Add(p18);

            var listItem6 = new Bold();
            listItem6.Inlines.Add("6) ");

            var p19 = new Paragraph();
            p19.Inlines.Add(listItem6);
            p19.Inlines.Add("Подвесная система фонов");

            word.Blocks.Add(p19);

            var listItem7 = new Bold();
            listItem7.Inlines.Add("7) ");

            var p20 = new Paragraph();
            p20.Inlines.Add(listItem7);
            p20.Inlines.Add("Стрипбокс 20*90, соты 2 шт");

            word.Blocks.Add(p20);

            var listItem8 = new Bold();
            listItem8.Inlines.Add("8) ");

            var p21 = new Paragraph();
            p21.Inlines.Add(listItem8);
            p21.Inlines.Add("Beauty dish 68 см");

            word.Blocks.Add(p21);

            var listItem9 = new Bold();
            listItem9.Inlines.Add("9) ");

            var p22 = new Paragraph();
            p22.Inlines.Add(listItem9);
            p22.Inlines.Add("Софтбокс Raylab  60x90 см");

            word.Blocks.Add(p22);

            var listItem10 = new Bold();
            listItem10.Inlines.Add("10) ");

            var p23 = new Paragraph();
            p23.Inlines.Add(listItem10);
            p23.Inlines.Add("Конусный рефлектор, соты, фильтры");

            word.Blocks.Add(p23);

            #endregion

            var p24 = new Paragraph();
            p24.Inlines.Add(new LineBreak());
            p24.Inlines.Add(new LineBreak());
            p24.Inlines.Add(new LineBreak());

            var tenant = new Bold();
            tenant.Inlines.Add("Арендатор");
            p24.Inlines.Add(tenant);
            p24.Inlines.Add(new LineBreak());
            p24.Inlines.Add(new LineBreak());

            var sign = new Bold();
            sign.Inlines.Add("Подпись");
            p24.Inlines.Add(sign);

            p24.Inlines.Add(new LineBreak());
            p24.Inlines.Add(new LineBreak());
            p24.Inlines.Add(new LineBreak());

            var thanks = new Bold();
            thanks.Inlines.Add("Спасибо!");

            p24.Inlines.Add(thanks);

            word.Blocks.Add(p24);

        }
示例#14
0
    public static FlowDocument PrintRecipe(Recipe r)
    {
      // Before printing check that all fields are valid
      if (r.Name == String.Empty || r.Time == String.Empty || r.Instructions == String.Empty || r.Writer == String.Empty)
      {
        throw new Exception("Reseptissä ei voi olla tyhjiä kenttiä!");
      }
      // If all fields are valid print the recipe
      else
      {
        // Create a FlowDocument
        FlowDocument doc = new FlowDocument();

        // Create a Section
        Section sec = new Section();
        Section sec2 = new Section();

        // Create first Paragraph
        Paragraph p1 = new Paragraph();
        Paragraph p2 = new Paragraph();

        // Create and add a new Bold, Italic and Underline
        Bold bld = new Bold();
        bld.Inlines.Add(new Run(r.Name));
        Italic italicBld = new Italic();
        italicBld.Inlines.Add(bld);
        Underline underlineItalicBld = new Underline();
        underlineItalicBld.Inlines.Add(italicBld);

        // Add Bold, Italic, Underline to Paragraph
        p1.Inlines.Add(underlineItalicBld);
        p1.Inlines.Add(new Run("\n" + r.Time));
        p1.Inlines.Add(new Run("\n" + r.Writer));

        p2.Inlines.Add(new Run(r.Instructions));

        // Add Paragraph to Section
        sec.Blocks.Add(p1);
        sec2.Blocks.Add(p2);

        // Add Section to FlowDocument
        doc.Blocks.Add(sec);
        doc.Blocks.Add(sec2);

        return doc;
      }
    }
        private UIElement GetLogControl(List<WorkReportLogEntity> logs, int rowIndex, int columnCount, int logCount,
            GridLength length)
        {
            int margin = 2;
            string groupName = Guid.NewGuid().ToString();
            var userLogControl = new LogGrid
            {
                Header = "LOG质量"
            };

            var gridLog = new Grid
            {
                ShowGridLines = false,

                Background = GetColor(5)
            };

            var logGroup = logs;
            if (logGroup.Count > 0)
            {
                for (int i1 = 0; i1 < columnCount + margin; i1++)
                {
                    if (i1==0)
                    {
                       gridLog.ColumnDefinitions.Add(new ColumnDefinition
                       {
                        Width =new GridLength(115),
                       });
                    }
                    else
                    {
                         gridLog.ColumnDefinitions.Add(new ColumnDefinition
                    {
                        Width =new GridLength(100),
                    });
                    }

                    Rectangle rec = CreateVertLine(i1, logGroup.Count + 1);

                    gridLog.Children.Add(rec);
                }

                for (int i1 = 0; i1 < logGroup.Count + 1; i1++)
                {
                    gridLog.RowDefinitions.Add(new RowDefinition
                    {
                        Height = GridLength.Auto,
                        MinHeight = 40
                    });
                    Rectangle rectSub = CreateHorLine(i1, columnCount + margin);
                    if (i1 == logGroup.Count() && rowIndex != logCount  * 2)
                    {
                        rectSub.Height = 2;
                        rectSub.Fill = new SolidColorBrush(Colors.Black);
                        rectSub.Margin = new Thickness(0, 1, 0, -1);
                    }
                    gridLog.Children.Add(rectSub);
                }

                Rectangle rectlogo = CreateRectangler(2);
                rectlogo.Margin = new Thickness(1);
                Grid.SetColumn(rectlogo, 0);
                Grid.SetColumnSpan(rectlogo,2);
                Grid.SetRow(rectlogo, 0);
                gridLog.Children.Add(rectlogo);

                var lableLogName = new Border
                {
                    Child = new TextBlock
                    {
                        Text = "LOG名称",
                        FontSize = 12,
                        FontWeight = FontWeights.Bold,
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Left,
                        Margin = new Thickness(20, 0, 0, 0)
                    },
                    Margin = new Thickness(1, 0, 1, 1)
                };
                lableLogName.SetValue(Canvas.ZIndexProperty, 10);
                Grid.SetColumn(lableLogName, 0);

                Grid.SetRow(lableLogName, 0);
                lableLogName.HorizontalAlignment = HorizontalAlignment.Stretch;
                lableLogName.VerticalAlignment = VerticalAlignment.Stretch;
                gridLog.Children.Add(lableLogName);

                var lableLogQuality = new Border
                {
                    Child = new TextBlock
                    {
                        Text = "Log质量",
                        FontSize = 12,
                        FontWeight = FontWeights.Bold,
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Left,
                        Margin = new Thickness(20, 0, 0, 0)
                    },
                    Margin = new Thickness(1, 0, 1, 1)
                };
                lableLogName.SetValue(Canvas.ZIndexProperty, 10);
                Grid.SetColumn(lableLogQuality, 1);

                Grid.SetRow(lableLogQuality, 0);
                lableLogName.HorizontalAlignment = HorizontalAlignment.Stretch;
                lableLogName.VerticalAlignment = VerticalAlignment.Stretch;
                gridLog.Children.Add(lableLogQuality);

                for (int m = 0; m < columnCount; m++)
                {
                    var kpi = logs[0].Kpis[m];
                    var lableLog = new TextBlock
                    {
                        Text = kpi.KpiName + (kpi.KpiName.Contains("FTP") ? "" : "(%)"),
                        FontSize = 12,
                        FontWeight = FontWeights.Bold,
                        MaxWidth = 80,
                        TextWrapping = TextWrapping.Wrap
                    };
                    lableLog.SetValue(ToolTipService.ToolTipProperty,
                        kpi.KpiName + (kpi.KpiName.Contains("FTP") ? "" : "(%)"));
                    Grid.SetColumn(lableLog, m + margin);
                    lableLog.VerticalAlignment = VerticalAlignment.Center;
                    lableLog.HorizontalAlignment = HorizontalAlignment.Center;
                    Grid.SetRow(lableLog, 0);
                    lableLog.SetValue(Canvas.ZIndexProperty, 10);
                    gridLog.Children.Add(lableLog);
                }

                var countLog = 0;
                for (int i = 0; i < logGroup.Count(); i++)
                {
                    countLog++;
                    StackPanel stackPanelLog = new StackPanel() {Orientation = Orientation.Horizontal};

                    var rb = new RadioButton() { Tag = logGroup[i], VerticalAlignment = VerticalAlignment.Center, GroupName = groupName+logGroup[i].LogServertype };
                    rb.SetBinding(RadioButton.IsCheckedProperty,
                        new Binding() { Source = rb.Tag, Path = new PropertyPath("IsSelected"), Mode = BindingMode.TwoWay });

                    stackPanelLog.Children.Add(rb);
                    var logtxt = new TextBlock
                    {
                        FontSize = 12,
                        FontWeight = FontWeights.Bold,
                        VerticalAlignment = VerticalAlignment.Center,
                        HorizontalAlignment = HorizontalAlignment.Left,
                        Margin = new Thickness(20, 0, 0, 0)
                    };
                    var run = new Run
                    {
                        Text = logGroup[i].LogName,
                    };
                    logtxt.Inlines.Add(run);
                    var br = new LineBreak();
                    logtxt.Inlines.Add(br);

                    var dataType = new Underline();

                    dataType.Inlines.Add(new Run
                    {
                        Text = logGroup[i].LogServertype + "(打点图)"
                    });
                    logtxt.Inlines.Add(dataType);
                    stackPanelLog.Children.Add(logtxt);
                    var lableNameLog1 = new Border
                    {
                        Child = stackPanelLog,
                        Margin = new Thickness(1, 0, 1, 1),
                        Cursor = Cursors.Hand
                    };

                    lableNameLog1.MouseLeftButtonDown +=
                        (s, e) =>
                        {
                        };
                    lableNameLog1.SetValue(Canvas.ZIndexProperty, 10);
                    Grid.SetColumn(lableNameLog1, 0);

                    Grid.SetRow(lableNameLog1, countLog);
                    lableNameLog1.VerticalAlignment = VerticalAlignment.Stretch;
                    lableNameLog1.HorizontalAlignment = HorizontalAlignment.Stretch;
                    gridLog.Children.Add(lableNameLog1);

                    Rectangle rectbg = CreateGridRowBackground(1, countLog);
                    gridLog.Children.Add(rectbg);

                    TextBlock logQuality = new TextBlock()
                    {
                        Foreground = GetColor(logGroup[i].Result),
                        FontFamily = new FontFamily("Microsoft YaHei"),
                        FontSize = 14,
                        FontWeight = FontWeights.Bold,

                    };

                    logQuality.Text = GetResult(logGroup[i].Result);
                    Grid.SetColumn(logQuality, 1);
                    Grid.SetRow(logQuality, countLog);
                    logQuality.VerticalAlignment = VerticalAlignment.Center;
                    logQuality.HorizontalAlignment = HorizontalAlignment.Center;
                    gridLog.Children.Add(logQuality);

                    if (logs[i].Kpis==null)
                    {
                        continue;
                    }
                    for (int m = 0; m < columnCount; m++)
                    {

                        var kpi = logs[i].Kpis[m];

                        Rectangle newrect = CreateRectangler(1);
                        newrect.Margin = new Thickness(1, 1, 1, 1);
                        Grid.SetColumn(newrect, m + margin);
                        Grid.SetRow(newrect, 0);
                        gridLog.Children.Add(newrect);

                        var borderlog = new TextBlock
                        {
                            Text =
                                kpi.KpiName.Contains("FTP")
                                    ? kpi.KpiValue.ToString()
                                    : (kpi.KpiValue.Value * 100).ToString("00.0"),
                            Foreground =GetColor(logs[i].Result),
                            FontFamily = new FontFamily("Microsoft YaHei"),
                            FontSize = 12,
                            VerticalAlignment = VerticalAlignment.Center,
                            HorizontalAlignment = HorizontalAlignment.Center
                        };

                        borderlog.SetValue(ToolTipService.ToolTipProperty,
                            kpi.KpiRange);
                        borderlog.SetValue(Canvas.ZIndexProperty, 100);
                        Grid.SetColumn(borderlog, m + margin);
                        Grid.SetRow(borderlog, countLog);
                        gridLog.Children.Add(borderlog);
                    }
                }
            }
            userLogControl.Content = new Border() { Child = gridLog,BorderBrush = new SolidColorBrush(Colors.Black),BorderThickness = new Thickness(1)}; ;

            return userLogControl;
        }
示例#16
0
        private static Inline GetInline(FrameworkElement element, SubtitleDescription description)
        {
            FontFamily fontFamily = null;
            if (description.FontFace != null)
                fontFamily = new FontFamily(description.FontFace);

            Style style = null;

            Inline inline = null;
            switch (description.Type)
            {
                case InlineType.Run:
                    var run = new Run(description.Text);
                    if (description.FontSize != null) run.FontSize = double.Parse(description.FontSize);
                    if (fontFamily != null) run.FontFamily = fontFamily;
                    inline = run;
                    break;
                case InlineType.LineBreak:
                    var lineBreak = new LineBreak();
                    inline = lineBreak;
                    break;
                case InlineType.Span:
                    var span = new Span();
                    inline = span;
                    break;
                case InlineType.Bold:
                    var bold = new Bold();
                    inline = bold;
                    break;
                case InlineType.Italic:
                    var italic = new Italic();
                    inline = italic;
                    break;
                case InlineType.Hyperlink:
                    var hyperlink = new Hyperlink();
                    inline = hyperlink;
                    break;
                case InlineType.Underline:
                    var underline = new Underline();
                    inline = underline;
                    break;
            }

            if (inline != null)
            {
                var span = inline as Span;
                if (span != null)
                {
                    var childInlines = new List<Inline>();
                    foreach (var inlineDescription in description.Subtitles)
                    {
                        var childInline = GetInline(element, inlineDescription);
                        if (childInline == null)
                            continue;

                        childInlines.Add(childInline);
                    }

                    span.Inlines.AddRange(childInlines);
                }
            }

            return inline;
        }