C# TextTrimming属性不适用于自定义TextBlock
我创建了一个“可绑定的”C# TextTrimming属性不适用于自定义TextBlock,c#,wpf,xaml,custom-controls,C#,Wpf,Xaml,Custom Controls,我创建了一个“可绑定的”TextBlock,即绑定到项目的TextBlock,这些项目具有定义文本应如何呈现的属性(例如颜色) 但是,“TextTrimming”属性不适用于我的自定义textblock,代码如下: class BindableTextBlock : TextBlock { public BindableTextBlock() { } public bool HideWhenEmpty { get { return (b
TextBlock
,即绑定到项目的TextBlock,这些项目具有定义文本应如何呈现的属性(例如颜色)
但是,“TextTrimming”属性不适用于我的自定义textblock,代码如下:
class BindableTextBlock : TextBlock
{
public BindableTextBlock()
{
}
public bool HideWhenEmpty
{
get { return (bool)GetValue(HideWhenEmptyProperty); }
set { SetValue(HideWhenEmptyProperty, value); }
}
public static readonly DependencyProperty HideWhenEmptyProperty =
DependencyProperty.Register("HideWhenEmpty", typeof(bool), typeof(BindableTextBlock), new UIPropertyMetadata(false));
public ObservableCollection<DescriptionToken> Items
{
get { return (ObservableCollection<DescriptionToken>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
public static readonly DependencyProperty ItemsProperty =
DependencyProperty.Register("Items", typeof(ObservableCollection<DescriptionToken>), typeof(BindableTextBlock), new UIPropertyMetadata(null, OnItemsPropertyChanged));
private static void OnItemsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
((BindableTextBlock)d).OnItemsChanged();
}
private void OnItemsChanged()
{
if (Items == null)
return;
Items.CollectionChanged -= ItemsCollectionChanged;
Items.CollectionChanged += ItemsCollectionChanged;
BuildText();
}
private void BuildText()
{
Inlines.Clear();
if (Items == null || !Items.Any())
{
if (HideWhenEmpty)
Visibility = System.Windows.Visibility.Collapsed;
return;
}
for (var i = 0; i < Items.Count; i++)
{
var item = Items[i];
var run = new Run(TruncateText(item.Text));
if (item.IsVariable)
{
run.Foreground = new SolidColorBrush(item.IsError ? Colors.Red : Colors.Blue);
run.FontStyle = FontStyles.Italic;
}
Inlines.Add(run);
}
Visibility = System.Windows.Visibility.Visible;
InvalidateVisual();
}
private string TruncateText(string text)
{
if (string.IsNullOrEmpty(text))
return text;
if (text.Contains(Environment.NewLine))
return TruncateText(text.Substring(0, text.IndexOf(Environment.NewLine)) + "...");
if (text.Length > 120)
{
var result = text.Substring(0, 120).TrimEnd('.');
return result + "...";
}
return text;
}
private void ItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
BuildText();
}
下图显示第一个文本块已修剪,但第二个(我的)未修剪:
如何使我的自定义TextBlock
与常规TextBlock
有关texttiming
属性的工作方式相同?如果控件换行,则无法进行修剪。
因此,请删除此代码:
TextWrapping = System.Windows.TextWrapping.Wrap;
从控件的构造函数中删除。为什么要向下投票???我后来删除了它(忘记了更新问题)。。我发誓我已经测试过了,但是是的,它是TextWrapping
。谢谢
TextWrapping = System.Windows.TextWrapping.Wrap;