我有一个自定义控件,我想告诉每个TextBlock
内部使用TextBlock.TextTrimming = CharacterEllipsis
,但我不想单独设置每个属性。我的意思是,即使稍后用户定义了ContentTemplate
并将其置于我的自定义控件中并且ContentTemplate
包含一些Textblocks
,他们也应该自动设置TextBlock.TextTrimming = CharacterEllipsis
。
我该怎么做?有什么帮助吗?
答案 0 :(得分:3)
您可以使用attached property创建property value inheritance并将其应用于自定义控件,例如在其构造函数中。只要目标对象是TextBlock,附加属性就会将其值复制到目标对象。
public class CustomControl : ContentControl
{
public CustomControl()
{
SetTextTrimming(this, TextTrimming.CharacterEllipsis);
}
public static readonly DependencyProperty TextTrimmingProperty =
DependencyProperty.RegisterAttached(
"TextTrimming", typeof(TextTrimming), typeof(CustomControl),
new FrameworkPropertyMetadata(
default(TextTrimming),
FrameworkPropertyMetadataOptions.Inherits,
TextTrimmingPropertyChanged));
public static TextTrimming GetTextTrimming(DependencyObject obj)
{
return (TextTrimming)obj.GetValue(TextTrimmingProperty);
}
public static void SetTextTrimming(DependencyObject obj, TextTrimming value)
{
obj.SetValue(TextTrimmingProperty, value);
}
private static void TextTrimmingPropertyChanged(
DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
var textBlock = obj as TextBlock;
if (textBlock != null)
{
textBlock.TextTrimming = (TextTrimming)e.NewValue;
}
}
}
请注意,无需在派生控件类中定义此TextTrimming
附加属性。您也可以在一个特殊的帮助器类中定义它,它甚至不需要从DependencyObject派生。
该属性也适用于在其可视化树中使用TextBoxes的任何其他控件,例如标准的ContentControl:
<ContentControl local:CustomControl.TextTrimming="WordEllipsis"
Content="Some sample text to be trimmed"/>