Binding the Text Property of a custom TextBlock which uses "new" Text Property

226 Views Asked by At

I have a custom TextBlock which overrides the base Text Property with new:

public new string Text
    {
        set
        {
            if (value == null) return;
            if (value.Equals(base.Text)) return;

            if (string.IsNullOrEmpty(value))
            {
                // Hide text
                SlideOut();
                FadeOut((_, _) =>
                    base.Text = value);
            }
            else if (!string.IsNullOrEmpty(base.Text))
            {
                // Hide, then show text
                SlideOut();
                FadeOut((_, _) =>
                {
                    base.Text = value;
                    SlideIn();
                    FadeIn();
                });
            }
            else
            {
                // Show text
                base.Text = value;
                SlideIn();
                FadeIn();
            }
        }
    }

I am a big fan of Binding, so I am trying to use it as such:

<customElements:AnimatedTextBlock
        x:Name="WarningTextBlock"
        Text="{Binding Warning}"
        FontWeight="Bold"
        Margin="4,8"
        TextWrapping="Wrap" />

OnPropertyChanged(); updates the Property of the TextBlock, but skips over my new Text Property. If I change back to a TextBlock, everything works fine.

I can manually apply WarningTextBlock.Text = "WARNING TEXT"; and it works, but I'd like to understand whether it's possible to target my new Property instead of the base TextBlock.Text with Binding.

1

There are 1 best solutions below

0
sjoshua270 On

After a bit of research with knowledge that I should look into DependencyProperty, I figured out how to implement it.

Here is the most helpful bit of code:

    public static readonly DependencyProperty TextContentProperty = DependencyProperty.Register(
        "TextContent", // Name of your actual Property
        typeof(string), // The type of your Property
        typeof(AnimatedTextBlock), // The type of the parent element
        new FrameworkPropertyMetadata(OnTextChanged)); // The method which is called after the base Property changes

    public string TextContent
    {
        // These are the first to get called
        get => (string) GetValue(TextContentProperty);
        set => SetValue(TextContentProperty, value);
    }

    private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var tb = (TextBlock) d;
        var newText = (string) e.NewValue;

        // Do things with your element
        // Such as: tb.Text = newText;
        // In my case, do animations            
    }