windows-8.1 – Windows应用程序确定TextBlock是否被修剪

前端之家收集整理的这篇文章主要介绍了windows-8.1 – Windows应用程序确定TextBlock是否被修剪前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个具有固定高度/宽度的GridItem.

它包含一个具有最大行集的文本块.

如何确定此文本是否已修剪?
我想添加特殊功能,如果它被修剪.

方法 – 当TextWrapping设置为None时

要知道是否修剪了TextBlock,我们可以订阅它的SizeChanged事件并将其ActualWidth与您指定的MaxWidth进行比较.要获得TextBlock的正确ActualWidth,我们需要将TextTrimming保留为其默认值(即TextTrimming.None),并在宽度超过时将其设置为trimmed.

方法 – 当TextWrapping设置为Wrap时

现在我知道因为TextWrapping设置为Wrap并假设未指定VirticalAlignment(默认为Stretch),Width将始终保持不变.当TextBlock的实际高度超过其父级的高度时,我们只需要监视SizeChanged事件.

让我们使用一个行为来封装上面的所有逻辑.这里需要提到的是,带有一堆附加属性的静态助手类或从TextBlock继承的新控件可以完全相同;但作为一个大混合粉丝,我更喜欢尽可能使用行为.

行为

  1. public class TextBlockAutoTrimBehavior : DependencyObject,IBehavior
  2. {
  3. public bool IsTrimmed
  4. {
  5. get { return (bool)GetValue(IsTrimmedProperty); }
  6. set { SetValue(IsTrimmedProperty,value); }
  7. }
  8.  
  9. public static readonly DependencyProperty IsTrimmedProperty =
  10. DependencyProperty.Register("IsTrimmed",typeof(bool),typeof(TextBlockAutoTrimBehavior),new PropertyMetadata(false));
  11.  
  12. public DependencyObject AssociatedObject { get; set; }
  13.  
  14. public void Attach(DependencyObject associatedObject)
  15. {
  16. this.AssociatedObject = associatedObject;
  17. var textBlock = (TextBlock)this.AssociatedObject;
  18.  
  19. // subscribe to the SizeChanged event so we will know when the Width of the TextBlock goes over the MaxWidth
  20. textBlock.SizeChanged += TextBlock_SizeChanged;
  21. }
  22.  
  23. private void TextBlock_SizeChanged(object sender,SizeChangedEventArgs e)
  24. {
  25. // ignore the first time height change
  26. if (e.PrevIoUsSize.Height != 0)
  27. {
  28. var textBlock = (TextBlock)sender;
  29.  
  30. // notify the IsTrimmed dp so your viewmodel property will be notified via data binding
  31. this.IsTrimmed = true;
  32. // unsubscribe the event as we don't need it anymore
  33. textBlock.SizeChanged -= TextBlock_SizeChanged;
  34.  
  35. // then we trim the TextBlock
  36. textBlock.TextTrimming = TextTrimming.WordEllipsis;
  37. }
  38. }
  39.  
  40. public void Detach()
  41. {
  42. var textBlock = (TextBlock)this.AssociatedObject;
  43. textBlock.SizeChanged += TextBlock_SizeChanged;
  44. }
  45. }

XAML

  1. <Grid HorizontalAlignment="Center" Height="73" VerticalAlignment="Center" Width="200" Background="#FFD2A6A6" Margin="628,329,538,366">
  2. <TextBlock x:Name="MyTextBlock" TextWrapping="Wrap" Text="test" FontSize="29.333">
  3. <Interactivity:Interaction.Behaviors>
  4. <local:TextBlockAutoTrimBehavior IsTrimmed="{Binding IsTrimmedInVm}" />
  5. </Interactivity:Interaction.Behaviors>
  6. </TextBlock>
  7. </Grid>

请注意,行为公开了依赖项属性IsTrimmed,您可以将数据绑定到viewmodel中的属性(在本例中为IsTrimmedInVm).

附:在WinRT中没有FormattedText函数,否则实现可能会有所不同.

猜你在找的Windows相关文章