WPF: Get “wrapped” text out of a textbox

后端 未结 4 659
执笔经年
执笔经年 2021-01-18 18:46

Is there a way in WPF to get the text formatted as it display on the textbox when TextWrapping=\"Wrap\"?



        
4条回答
  •  别那么骄傲
    2021-01-18 18:59

    If all you want is the text of textbox (complete text and not just the visible part), to be displayed as text (with apparent line breaks) on the same window in some textblock, a quick hack could be:

    FormattedText ft = new FormattedText(textBox1.Text,
        System.Globalization.CultureInfo.CurrentCulture,
        textBox1.FlowDirection,
        new Typeface(textBox1.FontFamily,
            textBox1.FontStyle,
            textBox1.FontWeight,
            textBox1.FontStretch),
        textBox1.FontSize,
        textBox1.Foreground);
    ft.TextAlignment = textBox1.TextAlignment;
    ft.Trimming = TextTrimming.None;
    
    ft.MaxTextWidth = textBox1.ViewportWidth;
    
    textBlock1.Width = textBox1.ViewportWidth;
    textBlock1.Height = ft.Height;
    
    textBlock1.TextAlignment = textBox1.TextAlignment;
    textBlock1.TextWrapping = textBox1.TextWrapping;
    textBlock1.Text = textBox1.Text;
    

    If its required in some other place, you can carry the values to that place and use them on the textblock there.

    If you need the complete text (with apparent line breaks) as a list of string (e.g. List) where each item represents the apparent line, you will need a complex solution.
    Also, if you need only the visible part of text as displayed in the textbox, again some complex solution is required.

提交回复
热议问题