Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

如何在TextBlock中拥有一个合适的Trimmed Text

From Wiki
Jump to: navigation, search
WP Metro Icon UI.png
SignpostIcon XAML 40.png
WP Metro Icon WP8.png
SignpostIcon WP7 70px.png
Article Metadata

兼容于
平台: Windows Phone 7.5 and later
Windows Phone 8
Windows Phone 7.5

文章
renlin 在 16 Mar 2013 创建
最后由 hamishwillee 在 28 Jun 2013 编辑

TextBlock本身提供了属性TextTrimming,但是其性能却不尽如人意。TextTriming其值可为WordTrim和None,当设置它为WorTrim时,如果字体长度超过TextBlock设置的最大宽度或高度时,系统会对文本进行剪切,这种剪切的效果常常对我们的UI效果带来不利的方。我们可以利用UserControl的MeasureOverride()方法进行一些操作使显示的Text更加符合我们的要求。

自定义一个UserControl,布局一个TextBlock来显示文本,并设置最大宽度值。

 <Grid x:Name="LayoutRoot">
<TextBlock x:Name="Content" MaxWidth="320" Text="" />
</Grid>

定义一个 Text属性,方便外部提供文本值。

 public string Text
{
get { return (string)GetValue(TextProperty); }
set
{
SetValue(TextProperty,value);
}
}
public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
"Text",
typeof(string),
typeof(MyTextBlock),
new PropertyMetadata(null,new PropertyChangedCallback(onTextChanged)));
private static void onTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
string value = (string)e.NewValue;
if (value != null)
((MyTextBlock)d).Content.Text = value;
 
((MyTextBlock)d).OnTextChanged(e);
}

在MeasureOverride()方法中进行文本宽度的判断,如果宽度大于最大宽度则对文本进行剪切

protected override Size MeasureOverride(Size availableSize)
{
 
Size originalSize = new Size(availableSize.Width, double.PositiveInfinity);
 
Size textSize = base.MeasureOverride(originalSize);
string reducedText = Content.Text;
while( textSize.Width>=Content.MaxWidth)
{
int prevLength = reducedText.Length;
 
reducedText = reducedText.Substring(0, reducedText.Length - 1);
if (prevLength == reducedText.Length)
{
break;
 
}
textSize = base.MeasureOverride(originalSize);
 
Content.Text = reducedText + "...";
 
}
return base.MeasureOverride(availableSize);
}
 
}

如图所示效果: TrimedText.png

This page was last modified on 28 June 2013, at 00:23.
210 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×