Maximum number of lines for a Wrap TextBlock

前端 未结 7 1724
心在旅途
心在旅途 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:12

    Based on @artistandsocial's answer, I created a attached property to set the maximum number of lines programatically (rather than having to overload TextBlock which is discouraged in WPF).

    public class LineHeightBehavior
    {
        public static readonly DependencyProperty MaxLinesProperty =
            DependencyProperty.RegisterAttached(
                "MaxLines",
                typeof(int),
                typeof(LineHeightBehavior),
                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)
        {
            var element = d as TextBlock;
            if (element != null)
            {
                element.MaxHeight = element.LineHeight * GetMaxLines(element);
            }
        }
    }
    

    By default, the LineHeight is set to double.NaN, so this value must first be set manually.

    The attached property MaxLines and other relevant properties can then be set in a Style:

    
    

提交回复
热议问题