我在Windows Phone 8应用程序中使用了包含许多元素的长列表选择器。每个项目都有一个文本块,每个文本的文本可以从几个字母到很多单词。我想将文本保持为一行,因此我将TextWrapping属性设置为“NoWrap”。我想添加“...”并裁剪文本,如果它太长而无法放在屏幕上。 到目前为止,我尝试使用每个TextBlock的加载事件并减少文本,直到它适合屏幕。但是,当列表包含许多元素时,不会为所有文本块激活加载事件。有没有正确的方法来解决这个问题?
private void TextBlock_Loaded_1(object sender, RoutedEventArgs e)
{
TextBlock txt = sender as TextBlock;
if (txt == null)
return;
if (txt.ActualWidth > 300)
{
while (txt.Text.Length > 4 && txt.ActualWidth > 290)
txt.Text = txt.Text.Substring(0, txt.Text.Length - 4);
txt.Text = txt.Text.Substring(0, txt.Text.Length - 3);
txt.Text = txt.Text.Trim(new Char[] { ' ', ',' }) + "...";
}
}
答案 0 :(得分:1)
以下是如何实现此目的的转换器示例:
using System;
using System.Globalization;
using System.Windows.Data;
namespace PhoneApp2
{
public class TextLengthConverter: IValueConverter
{
#region Implementation of IValueConverter
/// <summary>
/// Modifies the source data before passing it to the target for display in the UI.
/// </summary>
/// <returns>
/// The value to be passed to the target dependency property.
/// </returns>
/// <param name="value">The source data being passed to the target.</param><param name="targetType">The <see cref="T:System.Type"/> of data expected by the target dependency property.</param><param name="parameter">An optional parameter to be used in the converter logic.</param><param name="culture">The culture of the conversion.</param>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string)
{
int desiredLength;
if (int.TryParse(parameter.ToString(), out desiredLength))
{
if (desiredLength > 0)
{
string textIn = value as string;
if (textIn.Length > desiredLength // Make sure the truncation is actually needed.
&& textIn.Length > 3) // Make sure the length if the textIn is longer than the dots so 'something' is shown before the dots.
{
return textIn.Substring(0, desiredLength - 3) + "...";
}
}
}
}
return value;
}
/// <summary>
/// Modifies the target data before passing it to the source object. This method is called only in <see cref="F:System.Windows.Data.BindingMode.TwoWay"/> bindings.
/// </summary>
/// <returns>
/// The value to be passed to the source object.
/// </returns>
/// <param name="value">The target data being passed to the source.</param><param name="targetType">The <see cref="T:System.Type"/> of data expected by the source object.</param><param name="parameter">An optional parameter to be used in the converter logic.</param><param name="culture">The culture of the conversion.</param>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
#endregion
}
}
要在页面中使用它,请添加如下资源条目:
<phone:PhoneApplicationPage.Resources>
<PhoneApp2:TextLengthConverter x:Key="TextLengthConverter"/>
</phone:PhoneApplicationPage.Resources>
并将其附加到您的绑定文本:
<TextBlock Text="{Binding BoundText, Converter={StaticResource TextLengthConverter}, ConverterParameter=4}"/>
您可以添加到转换器集合中的一个不错的,可重复使用的解决方案。