【问题标题】:WPF Display formatted multiline text using data bindingWPF 使用数据绑定显示格式化的多行文本
【发布时间】:2011-01-18 10:45:49
【问题描述】:

我需要使用 WPF 数据绑定显示以下内容(值更改)。标题必须是粗体,信息行是普通文本。如果给定标题的信息不存在,我想折叠该部分,包括标题。我更喜欢所有数据(标题和信息项)都在一个格式化的字符串中,可以在我想要的地方换行。

标头1:

我的信息 1

我的信息 2

标头2:

我的信息 3

我的信息 4

【问题讨论】:

    标签: wpf data-binding text multiline formatted


    【解决方案1】:

    还有一种方法可以尝试。使用TextBlock.Inlines。然后将您的模型绑定到 TextBlock,并在自定义 value converter 中或通过自定义附加属性解析您的模型以填充 TextBlock 的内联。

    这是一个 Attached 属性的示例,它采用 Text 字符串并使每个第二个单词变为粗体:

    public class RunExtender : DependencyObject
    {
        public static string GetText(DependencyObject obj)
        {
            return (string)obj.GetValue(TextProperty);
        }
    
        public static void SetText(DependencyObject obj, string value)
        {
            obj.SetValue(TextProperty, value);
        }
    
        public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached("Text", typeof(string), typeof(RunExtender), new PropertyMetadata(string.Empty, OnBindingTextChanged));
    
        private static void OnBindingTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var bindingText = e.NewValue as string;
            var text = d as TextBlock;
            if (text != null)
            {
                text.Inlines.Clear();
                var words = bindingText.Split(' ');
                for (int i = 0; i < words.Length; i++)
                {
                    var word = words[i];
                    var inline = new Run() {Text = word + ' '};
                    if (i%2 == 0)
                    {
                        inline.FontWeight = FontWeights.Bold;
                    }
                    text.Inlines.Add(inline);
                }
            }
        }
    }
    

    这不是生产质量代码,它取自 Silverlight 演示,但你明白了。

    希望这会有所帮助。

    干杯,安瓦卡。

    【讨论】:

      【解决方案2】:

      如果您想以某种样式添加粗体,我认为最好的办法是将字符串分解并在StackPanel 中使用TextBlocksExpander 中。

      或者,您可以在 RichTextBox 中使用整个字符串来执行此操作,但我认为您的字符串必须包含 &lt;bold&gt;&lt;/bold&gt; 标签。

      【讨论】:

        猜你喜欢
        • 2011-05-02
        • 2012-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-12
        • 2010-10-04
        相关资源
        最近更新 更多