Question

I have a custom control and I would like to tell every TextBlock inside to use TextBlock.TextTrimming = CharacterEllipsis but I dont want to set that property on each individually. I mean even if later the user defines a ContentTemplate and places it inside my custom control and that ContentTemplate includes some Textblocks, they should automatically have set TextBlock.TextTrimming = CharacterEllipsis.

How do i do that? Any help please?

Was it helpful?

Solution

You could create an attached property with property value inheritance and apply that to your custom control, for example in its constructor. The attached property would copy its value to the target object, whenever the target object is a 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;
        }
    }
}

Note that there is no need to define this TextTrimming attached property in a derived control class. You could also define it in a special helper class, which does not even need to be derived from DependencyObject.

The property also work fine with any other control that uses TextBoxes in their visual tree, for example a standard ContentControl:

<ContentControl local:CustomControl.TextTrimming="WordEllipsis"
                Content="Some sample text to be trimmed"/>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top