WPF中哪种组件可以实现以下文字显示效果

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WPF中哪种组件可以实现以下文字显示效果相关的知识,希望对你有一定的参考价值。

如图所示,设计一个方法,输入是一个长的String,实现如图的显示方式,WPF中使用什么组件,怎样的处理方式,最好能够有代码,谢谢各位高手了

WPF中没有直接的控件能够达到这个效果,要自己写控件。给你写了个自定义控件的例子,代码如下:

【代码1】自定义控件RowTextPresenter,提供隔行效果的控件。(示例代码,仅仅封装了FontSize和FontFamily属性,你可以仿造示例自行封装)

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Data;

using System.Windows.Documents;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Imaging;

using System.Windows.Navigation;

using System.Windows.Shapes;

namespace WpfTextRow.Controls

    public class RowTextPresenter : FrameworkElement

    

        private TextBlock _textPresenter = new TextBlock();

        private DrawingVisual _rowsPresenter = new DrawingVisual();

        public RowTextPresenter()

        

            _textPresenter.TextWrapping = TextWrapping.Wrap;

            this.AddVisualChild(_rowsPresenter);

            this.AddVisualChild(_textPresenter);

        

        protected override int VisualChildrenCount

        

            get

            

                return 2;

            

        

        protected override Visual GetVisualChild(int index)

        

            if (index == 0) return _rowsPresenter;

            if (index == 1) return _textPresenter;

            throw new IndexOutOfRangeException();

        

        protected override void OnRender(DrawingContext drawingContext)

        

            base.OnRender(drawingContext);

            DrawRows();

        

        protected override Size MeasureOverride(Size availableSize)

        

            _textPresenter.Measure(availableSize);

            return _textPresenter.DesiredSize;

        

        protected override Size ArrangeOverride(Size finalSize)

        

            _textPresenter.Arrange(new Rect(new Point(0, 0), finalSize));

            return finalSize;

        

        private void DrawRows()

        

            if (_textPresenter == null || _rowsPresenter == null)

                return;

            var width = _textPresenter.ActualWidth;

            // 通过反射的方式获取折行的行数

            var lineCount = _textPresenter.ReflectGetProperty<int>("LineCount");

            var dc = _rowsPresenter.RenderOpen();

            if (lineCount > 1)

            

                var offsetY = 0.0;

                var baseValue = (this.AlternationMode == AlternationMode.Even) ? 1 : 0;

                for (int i = 0; i < lineCount; i++)

                

                    // 通过反射的方式获取每一行的高度

                    var lineMetrics = _textPresenter.ReflectCall("GetLine", i);

                    var lineHeight = lineMetrics.ReflectGetProperty<double>("Height");

                    // 判断奇偶行,绘制背景块

                    if (i % 2 == baseValue)

                    

                        dc.DrawRectangle(this.AlternationBackground, null, new Rect(0, offsetY, width, lineHeight));

                    

                    offsetY += lineHeight;

                

            

            dc.Close();

        

        #region FontSize

        public static readonly DependencyProperty FontSizeProperty =

            TextElement.FontSizeProperty.AddOwner(typeof(RowTextPresenter),

                new FrameworkPropertyMetadata((double)12.0));

        public double FontSize

        

            get  return (double)GetValue(FontSizeProperty); 

            set  SetValue(FontSizeProperty, value); 

        

        #endregion

        #region FontFamily

        /// <summary>

        /// FontFamily Dependency Property

        /// </summary>

        public static readonly DependencyProperty FontFamilyProperty =

            TextElement.FontFamilyProperty.AddOwner(typeof(RowTextPresenter),

                new FrameworkPropertyMetadata(null));

        /// <summary>

        /// Gets or sets the FontFamily property.  This dependency property 

        /// indicates ....

        /// </summary>

        public FontFamily FontFamily

        

            get  return (FontFamily)GetValue(FontFamilyProperty); 

            set  SetValue(FontFamilyProperty, value); 

        

        #endregion

        #region Text

        public static readonly DependencyProperty TextProperty =

            DependencyProperty.Register("Text", typeof(string), typeof(RowTextPresenter),

                new FrameworkPropertyMetadata(null,

                    FrameworkPropertyMetadataOptions.AffectsRender,

                    new PropertyChangedCallback(OnTextChanged)));

        public string Text

        

            get  return (string)GetValue(TextProperty); 

            set  SetValue(TextProperty, value); 

        

        private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        

            ((RowTextPresenter)d).OnTextChanged(e);

        

        protected virtual void OnTextChanged(DependencyPropertyChangedEventArgs e)

        

            _textPresenter.Text = (string)e.NewValue;

        

        #endregion

        #region AlternationBackground

        public static readonly DependencyProperty AlternationBackgroundProperty =

            DependencyProperty.Register("AlternationBackground", typeof(Brush), typeof(RowTextPresenter),

                new FrameworkPropertyMetadata(null,

                    FrameworkPropertyMetadataOptions.None,

                    new PropertyChangedCallback(OnAlternationBackgroundChanged)));

        public Brush AlternationBackground

        

            get  return (Brush)GetValue(AlternationBackgroundProperty); 

            set  SetValue(AlternationBackgroundProperty, value); 

        

        private static void OnAlternationBackgroundChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)

        

            ((RowTextPresenter)d).OnAlternationBackgroundChanged(e);

        

        protected virtual void OnAlternationBackgroundChanged(DependencyPropertyChangedEventArgs e)

        

            this.DrawRows();

        

        #endregion

        #region AlternationMode

        public static readonly DependencyProperty AlternationModeProperty =

            DependencyProperty.Register("AlternationMode", typeof(AlternationMode), typeof(RowTextPresenter),

                new FrameworkPropertyMetadata(AlternationMode.Even,

                    FrameworkPropertyMetadataOptions.AffectsRender));

        public AlternationMode AlternationMode

        

            get  return (AlternationMode)GetValue(AlternationModeProperty); 

            set  SetValue(AlternationModeProperty, value); 

        

        #endregion

    

    /// <summary>

    /// 跳行模式

    /// </summary>

    public enum AlternationMode

    

        /// <summary>

        /// 从偶数行开始

        /// </summary>

        Even,

        /// <summary>

        /// 从奇数行开始

        /// </summary>

        Odd

    

【代码2】ReflectionService,提供反射功能的工具类

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Reflection;

namespace WpfTextRow.Controls

    public static class ReflectionService

    

        private static readonly BindingFlags ReflectionFlags = 

            BindingFlags.Public | 

            BindingFlags.NonPublic | 

            BindingFlags.Instance;

        public static T ReflectGetProperty<T>(this object target, string propertyName)

        

            var type = target.GetType();

            var propertyInfo = type.GetProperty(propertyName, ReflectionFlags);

            return (T)propertyInfo.GetValue(target, null);

        

        public static object ReflectCall(this object target, string methodName, params object[] args)

        

            var type = target.GetType();

            var propertyInfo = type.GetMethod(methodName, ReflectionFlags);

            return propertyInfo.Invoke(target, args);

        

    

【代码3】使用的代码

<l:RowTextPresenter AlternationBackground="LightGreen"

                            FontSize="14"

                            Text="BEIJING—A study by China's Ministry of Commerce has found the European Union and its member states offered large subsidies to major telecommunications-infrastructure companies that Beijing views as a breach of World Trade Organization rules, a person familiar with the matter said Wednesday.The study, meant for internal distribution, could lay the foundation for a response by Beijing to any future punitive action by the EU following its recent investigation that found major Chinese telecom-equipment makers, such as Huawei Technologies Co. and ZTE Corp., benefited from significant financial backing from the Chinese government.The study by the commerce ministry found Brussels and EU member countries gave such subsidies by funding research-and-development projects, and by extending export credits and loans, said the person, who declined to be named." />

【效果图片】

来自:求助得到的回答
参考技术A 如果我来闹的话。。我宁愿这么做:
<StackPanel x:Name="bg">
</StackPanel>
<TextBlock x:Name="mytext" TextWrapping="Wrap" />

然后你可以在C#代码中根据mytext的字号来确定每行的高度,
从而循环创建Rectangle, 放置到bg中,Margin下方向=行高,Height=行高,Fill=你要的颜色。追问

那么怎样让这个string自动分行呢

追答

TextWrapping="Wrap" 就是啦

以上是关于WPF中哪种组件可以实现以下文字显示效果的主要内容,如果未能解决你的问题,请参考以下文章

WPF怎么样实现这种附加窗口的效果

WPF—QQ界面:联系人搜索框和个性签名一栏的效果实现

WPF,制作填空题

RHEL7有多种安装方式,以下几种方式中哪种是本地安装方式?

TextSwitcher实现文字上下翻牌效果

格子玻尔兹曼属于matlab中哪种算法