旧方法 – 当TextWrapping设置为None时
要知道是否修剪了TextBlock,我们可以订阅它的SizeChanged事件并将其ActualWidth与您指定的MaxWidth进行比较.要获得TextBlock的正确ActualWidth,我们需要将TextTrimming保留为其默认值(即TextTrimming.None),并在宽度超过时将其设置为trimmed.
新方法 – 当TextWrapping设置为Wrap时
现在我知道因为TextWrapping设置为Wrap并假设未指定VirticalAlignment(默认为Stretch),Width将始终保持不变.当TextBlock的实际高度超过其父级的高度时,我们只需要监视SizeChanged事件.
让我们使用一个行为来封装上面的所有逻辑.这里需要提到的是,带有一堆附加属性的静态助手类或从TextBlock继承的新控件可以完全相同;但作为一个大混合粉丝,我更喜欢尽可能使用行为.
行为
- public class TextBlockAutoTrimBehavior : DependencyObject,IBehavior
- {
- public bool IsTrimmed
- {
- get { return (bool)GetValue(IsTrimmedProperty); }
- set { SetValue(IsTrimmedProperty,value); }
- }
- public static readonly DependencyProperty IsTrimmedProperty =
- DependencyProperty.Register("IsTrimmed",typeof(bool),typeof(TextBlockAutoTrimBehavior),new PropertyMetadata(false));
- public DependencyObject AssociatedObject { get; set; }
- public void Attach(DependencyObject associatedObject)
- {
- this.AssociatedObject = associatedObject;
- var textBlock = (TextBlock)this.AssociatedObject;
- // subscribe to the SizeChanged event so we will know when the Width of the TextBlock goes over the MaxWidth
- textBlock.SizeChanged += TextBlock_SizeChanged;
- }
- private void TextBlock_SizeChanged(object sender,SizeChangedEventArgs e)
- {
- // ignore the first time height change
- if (e.PrevIoUsSize.Height != 0)
- {
- var textBlock = (TextBlock)sender;
- // notify the IsTrimmed dp so your viewmodel property will be notified via data binding
- this.IsTrimmed = true;
- // unsubscribe the event as we don't need it anymore
- textBlock.SizeChanged -= TextBlock_SizeChanged;
- // then we trim the TextBlock
- textBlock.TextTrimming = TextTrimming.WordEllipsis;
- }
- }
- public void Detach()
- {
- var textBlock = (TextBlock)this.AssociatedObject;
- textBlock.SizeChanged += TextBlock_SizeChanged;
- }
- }
XAML
- <Grid HorizontalAlignment="Center" Height="73" VerticalAlignment="Center" Width="200" Background="#FFD2A6A6" Margin="628,329,538,366">
- <TextBlock x:Name="MyTextBlock" TextWrapping="Wrap" Text="test" FontSize="29.333">
- <Interactivity:Interaction.Behaviors>
- <local:TextBlockAutoTrimBehavior IsTrimmed="{Binding IsTrimmedInVm}" />
- </Interactivity:Interaction.Behaviors>
- </TextBlock>
- </Grid>
请注意,行为公开了依赖项属性IsTrimmed,您可以将数据绑定到viewmodel中的属性(在本例中为IsTrimmedInVm).
附:在WinRT中没有FormattedText函数,否则实现可能会有所不同.