Just for people still in search of a "quick and simple" answer.
Using a converter can be a good way to go :
public class TextTrimmingConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string stringValue)
{
var paramInt = parameter?.ToInt(int.MaxValue); // this ToInt is custom, use whatever to convert your param (the max size of you textblock) into int
if (paramInt == int.MaxValue)
return stringValue;
var formattedText = new FormattedText(stringValue,
CultureInfo.GetCultureInfo("en-us"),
FlowDirection.LeftToRight,
new Typeface("Arial"),
14,
Brushes.Black);
var textWidth = formattedText.Width;
if (textWidth > paramInt)
return $"...{stringValue.Substring(stringValue.Length / 2)}"; // use a substring length that fits you
return stringValue;
}
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => Binding.DoNothing;
Then use it that way :
<TextBlock Text="{Binding MyTextToTrim,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay,Converter={StaticResource TextTrimmingConverter},ConverterParameter=150}"
MaxWidth="150"
VerticalAlignment="Center" />