WPF使用数据绑定显示格式化的多行文本 [英] WPF Display formatted multiline text using data binding

查看:443
本文介绍了WPF使用数据绑定显示格式化的多行文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to display the following using WPF databinding (the values change). Headers must be bold, the info lines are normal text. If info for a given header does not exist, I want to collapse that section, including the header. I prefer all the data (header and info items) be in one formatted string that can line break where I want.

标题1:

我的信息1

我的信息2

标题2:

我的info 3

我的信息4

推荐答案

。使用 TextBlock.Inlines 。然后将您的模型绑定到TextBlock,并在自定义值转换器或通过自定义附加属性解析您的模型以填充TextBlock的内联。

One more approach to try. Use TextBlock.Inlines. Then bind your model to the TextBlock, and either in custom value converter or via custom attached property parse your model to populate TextBlock's inlines.

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

Here is an example of Attached property that takes Text string and makes every second word bold:

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演示,但是你可以得到这个想法。

This is not a production quality code, and it's taken from Silverlight demo, but you get the idea.

希望这有帮助。

干杯,Anvaka。

这篇关于WPF使用数据绑定显示格式化的多行文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆