How can I determine if my TextBlock text is being trimmed?

后端 未结 5 1597
被撕碎了的回忆
被撕碎了的回忆 2020-11-30 01:02

The following textblock wraps and trims as expected. The elipsis \"...\" is displayed when the text is trimmed.



        
5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 01:48

    The solution above didn't work for me if the TextBlock is part of a ListBoxItem DataTemplate. I propose another solution:

    public class MyTextBlock : System.Windows.Controls.TextBlock
    {
    
        protected override void OnToolTipOpening(WinControls.ToolTipEventArgs e)
        {
            if (TextTrimming != TextTrimming.None)
            {
                e.Handled = !IsTextTrimmed(); 
            }
        }
    
        private bool IsTextTrimmed()
        {
            Measure(new Size(Double.PositiveInfinity, Double.PositiveInfinity));
            return ActualWidth < DesiredSize.Width;
        }
    }
    

    XAML:

      
    

提交回复
热议问题