コード例 #1
0
 /// <summary>
 /// 将 HighlightText 依赖项属性的值设置为指定元素。
 /// </summary>
 /// <param name="obj">对其设置属性值的元素。</param>
 /// <param name="value">要设置的值。</param>
 public static void SetHighlightText(TextBlock textBlock, TextBlockHighlightSource value) => textBlock.SetValue(HighlightTextProperty, value);
コード例 #2
0
        private static void MarkHighlight(TextBlock target, TextBlockHighlightSource highlightSource)
        {
            var text = target.Text;

            target.Inlines.Clear();
            if (string.IsNullOrWhiteSpace(text))
            {
                return;
            }

            if (string.IsNullOrWhiteSpace(highlightSource.Text))
            {
                target.Inlines.Add(new Run {
                    Text = text
                });
                return;
            }

            while (text.Length > 0)
            {
                var runText = string.Empty;
                var index   = text.IndexOf(highlightSource.Text, StringComparison.InvariantCultureIgnoreCase);
                if (index > 0)
                {
                    runText = text.Substring(0, index);
                    var run = new Run
                    {
                        Text = runText,
                    };
                    if (highlightSource.LowlightForeground != null)
                    {
                        run.Foreground = highlightSource.LowlightForeground;
                    }

                    target.Inlines.Add(run);
                }
                else if (index == 0)
                {
                    runText = text.Substring(0, highlightSource.Text.Length);
                    var run = new Run {
                        Text = runText
                    };
                    if (highlightSource.HighlightForeground != null)
                    {
                        run.Foreground = highlightSource.HighlightForeground;
                    }

                    if (highlightSource.HighlightBackground != null)
                    {
                        run.Background = highlightSource.HighlightBackground;
                    }

                    target.Inlines.Add(run);
                }
                else if (index == -1)
                {
                    runText = text;
                    var run = new Run
                    {
                        Text = runText,
                    };
                    if (highlightSource.LowlightForeground != null)
                    {
                        run.Foreground = highlightSource.LowlightForeground;
                    }

                    target.Inlines.Add(run);
                }

                text = text.Substring(runText.Length);
            }
        }