Maximum number of lines for a Wrap TextBlock

前端 未结 7 1664
心在旅途
心在旅途 2021-02-05 02:40

I have a TextBlock with the following setting:

TextWrapping=\"Wrap\"

Can I determine the maximum number of lines?

for exam

7条回答
  •  面向向阳花
    2021-02-05 03:05

    Based tobi.at's and gt's answer I have created this MaxLines behaviour. Crucially it doesn't depend upon setting the LineHeight property by calculating the line height from the font. You still need to set TextWrapping and TextTrimming for it the TextBox to be render as you would like.

    
    

    There in also a MinLines behaviour which can be different or set to the same number as the MaxLines behaviour to set the number of lines.

    public class NumLinesBehaviour : Behavior
    {
        TextBlock textBlock => AssociatedObject;
    
        public static readonly DependencyProperty MaxLinesProperty =
            DependencyProperty.RegisterAttached(
                "MaxLines",
                typeof(int),
                typeof(NumLinesBehaviour),
                new PropertyMetadata(default(int), OnMaxLinesPropertyChangedCallback));
    
        public static void SetMaxLines(DependencyObject element, int value)
        {
            element.SetValue(MaxLinesProperty, value);
        }
    
        public static int GetMaxLines(DependencyObject element)
        {
            return (int)element.GetValue(MaxLinesProperty);
        }
    
        private static void OnMaxLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TextBlock element = d as TextBlock;
            element.MaxHeight = getLineHeight(element) * GetMaxLines(element);
        }
    
        public static readonly DependencyProperty MinLinesProperty =
            DependencyProperty.RegisterAttached(
                "MinLines",
                typeof(int),
                typeof(NumLinesBehaviour),
                new PropertyMetadata(default(int), OnMinLinesPropertyChangedCallback));
    
        public static void SetMinLines(DependencyObject element, int value)
        {
            element.SetValue(MinLinesProperty, value);
        }
    
        public static int GetMinLines(DependencyObject element)
        {
            return (int)element.GetValue(MinLinesProperty);
        }
    
        private static void OnMinLinesPropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            TextBlock element = d as TextBlock;
            element.MinHeight = getLineHeight(element) * GetMinLines(element);
        }
    
        private static double getLineHeight(TextBlock textBlock)
        {
            double lineHeight = textBlock.LineHeight;
            if (double.IsNaN(lineHeight))
                lineHeight = Math.Ceiling(textBlock.FontSize * textBlock.FontFamily.LineSpacing);
            return lineHeight;
        }
    }
    

提交回复
热议问题