The old way is when Text Print is set to None
To find out if a TextBlock is TextBlock , we can subscribe to its SizeChanged event and compare its ActualWidth with the MaxWidth you MaxWidth . To get ActualWidth for the TextBlock to the right , we need to leave the default TextTrimming value (i.e. TextTrimming.None ) and set it to trim after the width has passed.
New way - when installing TextWrapping on Wrap
Now that I know, because TextWrapping set to Wrap and it is assumed that VirticalAlignment not specified (by default Stretch ), Width will always remain the same. We only need to track the SizeChanged event when the actual height of the TextBlock exceeds the height of the parent element.
Let Behavior be used to encapsulate all of the above logic. It is worth mentioning here that a static helper class with a bunch of attached properties or a new control that inherits from TextBlock can do the same; but as a big fan of Blend, I prefer to use the Behaviors whenever possible.
Behavior
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;
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>
Note that Behavior provides the IsTrimmed dependency IsTrimmed , you can bind it to a property in your viewmodel (i.e., IsTrimmedInVm in this case).
PS There is no FormattedText function in FormattedText , otherwise the implementation may be slightly different.