WPF Display formatted multiline text using data binding

断了今生、忘了曾经 提交于 2019-12-01 11:26:21

问题


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.

Header1:

My info 1

My info 2

Header2:

My info 3

My info 4


回答1:


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.

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);
            }
        }
    }
}

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

Hope this helps.

Cheers, Anvaka.




回答2:


If you want to do the bolding in a style I think your best bet would be to break your string up and use TextBlocks within a StackPanel within an Expander.

Alternatively you could do it in a RichTextBox with your whole string, but I think your string would have to contain the <bold></bold> tags.



来源:https://stackoverflow.com/questions/2290812/wpf-display-formatted-multiline-text-using-data-binding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!